package com.yantong.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.yantong.config.LocalRedis;
import com.yantong.constant.*;
import com.yantong.enums.*;
import com.yantong.mapper.*;
import com.yantong.pay.yfz.domain.pay.domain.split.SplitInfo;
import com.yantong.pay.yfz.domain.pay.domain.split.SplitRequest;
import com.yantong.pay.yfz.domain.pay.domain.split.SplitResponse;
import com.yantong.pay.yfz.pay.YFZPayutil;
import com.yantong.pojo.Activity;
import com.yantong.pojo.ActivityProduct;
import com.yantong.pojo.ActivityProductExample;
import com.yantong.pojo.Centre;
import com.yantong.pojo.vo.*;
import com.yantong.service.*;
import com.yantong.exception.BDException;
import com.yantong.utils.*;
import com.yantong.pojo.BalanceLog;
import com.yantong.pojo.CommissionLog;
import com.yantong.pojo.Payment;
import com.yantong.pojo.PayChannel;
import com.yantong.pojo.MarketingGroup;
import com.yantong.pojo.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import static com.yantong.constant.CacheKeyLocal.CLOSED_ORDER;

/**
 * 支付服务
 *
 * @author kanghaixin
 * @date 2018/9/29.9:50
 */
@Service
public class PayServiceImpl implements PayService {
	private static Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private TicketRecordMapper ticketRecordMapper;
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private BalanceService balanceService;
	@Autowired
	private ProjectExpService projectExpService;
	@Autowired
	private PaymentService paymentService;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private ConfigService configService;
	@Autowired
	private MemberIntegralService integralService;
	@Autowired
	private LocalRedis localRedis;
	@Autowired
	private CentreService centreService;
	@Autowired
	private CentreMapper centreMapper;
	@Autowired
	private ProductCentreService productCentreService;
	@Autowired
	private ProductService productService;
	@Autowired
	PayChannelService payChannelService;
	@Autowired
	private BalanceLogMapper balanceLogMapper;
	@Autowired
	private MemberService memberService;
	@Autowired
	private JuheOrderMapper juheOrderMapper;
	@Autowired
	@Lazy
	private OrderService orderService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private MarketingGroupMapper marketingGroupMapper;
	@Autowired
	private MemberRoleService memberRoleService;
	@Autowired
	private MemberWalletService memberWalletService;
	@Autowired
	private CommissionService commissionService;
	@Autowired
	private ActivityProductMapper activityProductMapper;
	@Autowired
	private ActivityMapper activityMapper;
	@Autowired
	private TicketService ticketService;
	@Autowired
	private MyWxpayService myWxpayService;
	@Autowired
	private BalanceLogService balanceLogService;
	@Autowired
	private MemberUseragentMapper memberUseragentMapper;
	@Value("${Applet.TemplatemsgCreateUserUrl}")
	private String templatemsgCreateUserUrl;

	@Value("${weixin.miniapps.appid}")
	private String wxMiniAppsAppId;
	@Value("${weixin.appid}")
	private String wxAppId;
	@Value("${weixin.mchId}")
	private String wxMchId;
	@Value("${weixin.ip}")
	private String wxIp;
	@Value("${weixin.enterprice.url}")
	private String wxEnterpriceUrl;
	@Value("${weixin.certificate.path}")
	private String wxcertificatePath;
	@Value("${weixin.pay.signkey}")
	private String paySignKey;
	@Autowired
	private WxNotifyService wxNotifyService;
	@Autowired
	private StoreFreechargeMapper storeFreechargeMapper;
	@Autowired
	private TicketMapper ticketMapper;
	@Autowired
	private CommissionLogMapper commissionLogMapper;

	@Autowired
	private MemberIntegralService memberIntegralServicep;
	@Autowired
	private OrderSplitInfoMapper orderSplitInfoMapper;
	@Autowired
	private UsableTeamMiddleMapper usableTeamMiddleMapper;
	@Autowired
	@Lazy
	private PayService payService;


	@Override
	public String refreshTradeNo(Long orderId) {
		if (orderId == null) {
			logger.info("refreshTradeNo orderId is null!");
			return null;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (order == null) {
			logger.info("not found order by orderId:{}", orderId);
			return null;
		}
		String no = CommonUtils.getSn("X_OC_D");
		order.setOutTradeNo(no);
		order.setPayMerchantNo(no);
		orderMapper.updateByPrimaryKeySelective(order);
		return no;
	}

	@Override
	public double getPrePayAmount(Order order, Integer integral) {
		// BigDecimal payPrice = order.getOrderprice().subtract(order.getDiscountprice());
		//加上邮费
		BigDecimal payPrice = order.getOrderprice().subtract(order.getDiscountprice());
		if (integral != null) {
			//BigDecimal deductPrice = this.calcIntegralDeductPrice(integral);修改之前
			BigDecimal deductPrice = this.calcIntegralDeductPrice(integral, order.getCentreId());
			payPrice = payPrice.subtract(deductPrice);
		}
		if (payPrice.doubleValue() < 0) {
			payPrice = BigDecimal.valueOf(0);
		}
		return payPrice.doubleValue();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int balancePay(String orderId, Integer integral) {
		if (orderId == null) {
			logger.info("balance pay orderId is null!");
			return 0;
		}
		List<Order> orders;
		if (orderId.contains("X_OC_")) {
			orders = orderMapper.selectOrderByOutTradeNo(orderId);

		} else {
			OrderExample orderExample = new OrderExample();
			orderExample.createCriteria().andIdEqualTo(Long.parseLong(orderId));
			orders = orderMapper.selectByExample(orderExample);
		}
		if (CollectionUtils.isEmpty(orders)) {
			logger.info("balance pay not found order by id:{}", orderId);
			return 0;
		}
		// Order order = orderMapper.getByPayNoSumPrice(orderId);
		Order order = orders.get(0);

		if (order.getStatus() != OrderStatus.wait_pay.getCode()) {
			logger.info("order already pay,please check!");
			throw new BDException(BusinessCode.ORDER_PAYED_ERROR);
		}
		BigDecimal totalPayPrice = new BigDecimal("0");
		BigDecimal totalDispatchprice = new BigDecimal("0");
		Date now = new Date();
		for (Order order1 : orders) {
			BigDecimal payPrice = order1.getPayprice();
			if (payPrice.doubleValue() >= 0) {
				order.setPayprice(payPrice);
			} else {
				order.setPayprice(BigDecimal.ZERO);
			}
			totalPayPrice = totalPayPrice.add(order.getPayprice());
		}
		BigDecimal deductPrice = null;
		if (integral != null) {
			//deductPrice = this.calcIntegralDeductPrice(integral);修改之前
			deductPrice = this.calcIntegralDeductPrice(integral, order.getCentreId());
			//payPrice = payPrice.subtract(deductPrice);

		}
		for (Order order1 : orders) {
			order1.setPaytype(PayType.BALANCE_PAY);
			orderMapper.updateByPrimaryKeySelective(order1);
			//将佣金记录激活
			commissionService.activeCommissionLog(order1.getId());

			BigDecimal payPrice = order1.getPayprice();
			BigDecimal divide1 = new BigDecimal("0");
			if (totalPayPrice.doubleValue() > 0) {
				//单独订单除以总数
				divide1 = payPrice.divide(totalPayPrice, 2, BigDecimal.ROUND_HALF_UP);
			}
			if (deductPrice != null) {
				//payPrice = payPrice.subtract(deductPrice);
				BigDecimal multiply = deductPrice.multiply(divide1);
				payPrice = payPrice.subtract(multiply);
				order1.setDeductprice(multiply);
				Double aDouble = divide1.doubleValue() * integral;
				order1.setDeductcredit(aDouble.intValue());
				//totalPayPrice= totalPayPrice.subtract(multiply);
			}

			if (payPrice.doubleValue() >= 0) {
				order1.setPayprice(payPrice);
			} else {
				order1.setPayprice(BigDecimal.valueOf(0));
			}
			//totalPayPrice =order.getPayprice().add(order.getPayprice());
			OrderProductExample ope = new OrderProductExample();
			ope.or().andOrderidEqualTo(order1.getId());
			OrderProduct op = new OrderProduct();
			//1是 0不是
			if (order1.getIsCentreord() != null && order1.getIsCentreord() == 1) {
				//是站长支付商品 状态变为已完成
				op.setStatus(OrderStatus.success.getCode());
			} else if (order1.getOrderType() == ProductType.Package.getType()) {
				this.packageCallback(Long.valueOf(orderId), order.getMid(), op, order1);
			}
			//免单优惠券
			else if (order1.getOrderType() == ProductType.FreeCharge.getType()) {
				this.freeChargeCallback(Long.valueOf(orderId), order, op, order1);
				op.setStatus(OrderStatus.success.getCode());
				order1.setStatus(OrderStatus.success.getCode());
			} else {
				//不是站长支付商品 状态变为待发货
				op.setStatus(OrderStatus.wait_send.getCode());
			}
			op.setPayStatus(PayStatus.PAY_SUCCESS.getCode());
			op.setPayTime(now);
			orderProductMapper.updateByExampleSelective(op, ope);

			//得到订单商品供应商信息
			//List<OrderProduct> supList = orderProductMapper.getProductSupplierInfo(order1.getId());
			//SmsUtil.sendSupply(supList);

			order1.setDeductcredit2(order1.getPayprice());
			//1是 0不是
			if (order1.getIsCentreord() != null && order1.getIsCentreord() == 1
					&& order1.getIsupgrade() != 1) {
				//不是站长支付商品 状态变为已完成
				order1.setStatus(OrderStatus.success.getCode());
				Centre record = new Centre();
				record.setMid(order1.getMid());
				record.setPayStatus(PayStatus.PAY_SUCCESS.getCode());
				//修改站点支付状态
				centreMapper.updateByMid(record);
			} else {
				//不是站长支付商品 状态变为待发货
				order1.setStatus(OrderStatus.wait_send.getCode());
				if (order1.getOrderType() == ProductType.FreeCharge.getType()) {
					order1.setStatus(OrderStatus.success.getCode());
				}
			}
			if (order1.getIsupgrade() != null && order1.getIsupgrade() == 1) {
				//得到订单商品信息
				List<OrderProduct> ops = orderProductMapper.getProductListByOrderId(order1.getId());
				//版本对象
				ProjectExpVo params = new ProjectExpVo();
				params.setType(0);
				params.setId(ops.get(0).getProjectexpId());
				//得到版本
				ProjectExp projectExp = projectExpService.listProjectExp(params);
				//用户对象
				Member member = new Member();
				member.setId(order1.getMid());
				//更新用户版本信息
				// memberMapper.updateByPrimaryKeySelective(member);
				memberService.updateMember(member);
				Centre record = new Centre();
				record.setMid(order1.getMid());
				record.setProjectexpId(projectExp.getId());
				record.setProjectexpName(projectExp.getName());
				record.setProjectexpPrice(projectExp.getPrice());
				//修改站点版本信息
				centreMapper.updateByMid(record);
				//不是站长支付商品 状态变为已完成
				order1.setStatus(OrderStatus.success.getCode());
			}
			order1.setPaystatus(PayStatus.PAY_SUCCESS.getCode());
			order1.setPayTime(now);
			//order1.setPaytype(PayType.BALANCE_PAY);
			orderMapper.updateByPrimaryKeySelective(order1);
			//拼团订单
			logger.info("===============拼团逻辑开始================");
			if (order1.getOrderType() == ProductType.Spellgroup.getType()) {
				int result = verificationSpellGroup(order1);
				if (result < 0) {
					logger.info("拼团订单回掉修改人数失败");
				}
			}
			logger.info("===============拼团逻辑结束================");

		}
		if (deductPrice != null) {
			totalPayPrice = totalPayPrice.subtract(deductPrice);
		}
		Member member = memberMapper.selectByPrimaryKey(order.getMid());
		if (member == null) {
			throw new BDException(BusinessCode.MEMBER_INFO_ISNULL);
		}
		if (totalPayPrice.subtract(member.getCredit2() == null ? BigDecimal.ZERO : member.getCredit2()).doubleValue() > 0) {
			throw new BDException(BusinessCode.MEMBER_BALANCE_NOT_ENOUGH);
		}

		paymentService.savePayment(order);
		balanceService.deduct(order.getMid(), totalPayPrice.add(totalDispatchprice).doubleValue(), BalanceLogStyle.ORDER_DEDUCT.getCode(),
				RechargeType.ORDER_DEDUCT.getType(), order.getOrdersn(), null, null);

		//积分扣款
		integralService.consumerGrantIntegralNew2(order);

		if (integral != null) {
			/*integralService.consumerIntegral(order.getMid(), integral, order.getOrdersn());*/
			//鲍凌宇-消费积分
			integralService.consumerGrantIntegralNew(order, integral);
			logger.info("integral consume success,mid:{},integral:{}", order.getMid(), integral);
		}

		return 1;
	}
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int wxPay(Long orderId, String payNo, String outTradeNo, Integer integral, Long procedureFee) {
		if (orderId == null || StringUtils.isEmpty(payNo)) {
			logger.info("wxPay orderId or payNo is null!");
			return 0;
		}
		logger.info("进来了wxPay==================");
		List<Order> orders = orderMapper.selectOrderByOutTradeNo(outTradeNo);
		if (CollectionUtils.isEmpty(orders)) {
			logger.info("balance pay not found order by id:{}", orderId);
			return 0;
		}
		// Order order = orderMapper.getByPayNoSumPrice(orderId);
		Order order = orders.get(0);

		BigDecimal totalPayPrice = new BigDecimal("0");
		Date now = new Date();
		for (Order order1 : orders) {
			BigDecimal payPrice = order1.getOrderprice().subtract(order1.getDiscountprice());
			totalPayPrice = totalPayPrice.add(order.getPayprice());
		}
		BigDecimal deductPrice = null;
		if (integral != null) {
			//deductPrice = this.calcIntegralDeductPrice(integral);修改之前
			deductPrice = this.calcIntegralDeductPrice(integral, order.getCentreId());
			//payPrice = payPrice.subtract(deductPrice);

		}
		//查询支付通道
		PayChannel payChannel = payChannelService.getFirstChannel(order.getCentreId());
		for (Order order1 : orders) {
			//将佣金记录激活
			commissionService.activeCommissionLog(order1.getId());

			BigDecimal payPrice = order1.getPayprice();
			BigDecimal divide1 = new BigDecimal("0");
			if (totalPayPrice.doubleValue() > 0) {
				divide1 = payPrice.divide(totalPayPrice, 2, BigDecimal.ROUND_HALF_UP);
			}


			if (deductPrice != null) {
				//payPrice = payPrice.subtract(deductPrice);
				BigDecimal multiply = deductPrice.multiply(divide1);
//                payPrice = payPrice.subtract(multiply);
				order1.setDeductprice(multiply);
				Double aDouble = divide1.doubleValue() * integral;
				order1.setDeductcredit(aDouble.intValue());
				//totalPayPrice= totalPayPrice.subtract(multiply);
			}


			OrderProductExample ope = new OrderProductExample();
			ope.or().andOrderidEqualTo(order1.getId());
			OrderProduct op = new OrderProduct();
			//商户升级或者商户开户，或者是套装
			if ((order1.getIsCentreord() != null && order1.getIsCentreord() == 1)
					|| (order1.getIsCentreUpgrade() != null && order1.getIsCentreUpgrade() == 1)
					|| (order1.getIsStores() != null && order1.getIsStores() == 1)) {
				//是站长支付商品 状态变为已完成
				op.setStatus(OrderStatus.success.getCode());
			} else if (order1.getOrderType() == ProductType.Package.getType()) {
				this.packageCallback(orderId, order.getMid(), op, order1);
			}
			//免单优惠券  大礼包
			else if (order1.getOrderType() == ProductType.FreeCharge.getType()) {
				this.freeChargeCallback(orderId, order, op, order1);
				op.setStatus(OrderStatus.success.getCode());
				order1.setStatus(OrderStatus.success.getCode());
			} else {
				//不是站长支付商品 状态变为已发货
				op.setStatus(OrderStatus.wait_send.getCode());
			}
			op.setPayStatus(PayStatus.PAY_SUCCESS.getCode());
			op.setPayTime(now);
			orderProductMapper.updateByExampleSelective(op, ope);

			//得到订单商品供应商信息
//            List<OrderProduct> supList = orderProductMapper.getProductSupplierInfo(order1.getId());
//            SmsUtil.sendSupply(supList);

			List<OrderProduct> list = orderProductMapper.getByOrderId(order.getId());
			//order1.setDeductcredit2(order1.getPayprice());
			//0不是 1是
			if (order1.getIsCentreord() != null && order1.getIsCentreord() == 1) {
				//是站长支付商品 状态变为已完成
				order1.setStatus(OrderStatus.success.getCode());
				//得到订单商品信息
				List<OrderProduct> ops = orderProductMapper.getProductListByOrderId(order1.getId());
				//版本对象
				ProjectExpVo params = new ProjectExpVo();
				params.setType(0);
				params.setId(ops.get(0).getProjectexpId());
				//得到版本
				ProjectExp projectExp = projectExpService.listProjectExp(params);

				//用户对象
				Member member = new Member();
				member.setId(order1.getMid());
				//更新用户版本信息
				//memberMapper.updateByPrimaryKeySelective(member);
				memberService.updateMember(member);

				//有效期
				BuyProjectVo buyProjectVo = orderService.calcProjectExpCharge(member, ops.get(0).getTotal(), projectExp);

				Centre record = centreMapper.queryByRenewMid(order1.getMid());
//				record.setRenewMid(order1.getMid());
				record.setProjectexpId(projectExp.getId());
				record.setProjectexpName(projectExp.getName());
				record.setProjectexpPrice(projectExp.getPrice());
				record.setExpiredDate(buyProjectVo.getExpiredDate());
				record.setPayStatus(PayStatus.PAY_SUCCESS.getCode());
				if (buyProjectVo.getIsupgrade().equals(1)) {
					//免费版升级收费版改为待审核
					record.setStatus("2");
				}
				//修改站点支付状态
				int count = centreMapper.updateByRenewMid(record);

				//查询相应的资产赠送额度
				AssetConfig assetConfig = configService.getAssetConfig(order1.getCentreId());
				//给用户添加资产
				Member memberParam = new Member();
				memberParam.setId(order1.getMid());
				MemberWallet memberWallet = memberWalletService.findById(memberParam);
				if (memberWallet != null && null != assetConfig && assetConfig.getYearCombo() != null) {
					memberWallet.setAA(memberWallet.getAA().add(BigDecimal.valueOf(assetConfig.getYearCombo())));
					memberWalletService.update(memberWallet);
					//添加资产转入记录
					memberWalletService.insertLog(new MemberWalletLog(memberWallet.getEADD(), memberWallet.getMemberId(), WalletLogTypeEnum.AA.getCode(),
							WalletLogOperationTypeEnum.INCOME.getCode(), BigDecimal.valueOf(assetConfig.getYearCombo()), 100d));
				}

				//直推分佣
				Member memberResult = memberService.getByKey(order1.getMid());
				Member referrerMember = null;
				if (memberResult != null && memberResult.getUserid() != null) {
					referrerMember = memberService.getByKey(memberResult.getUserid());
				}

				if (referrerMember != null) {

					//获取佣金配置信息
					CommisConfig commisConfig = configService.getCommissionConfig(referrerMember.getCentreId());
					if (null != commisConfig) {
						//佣金
						BigDecimal commission = BigDecimal.ZERO;

						double ratio = 0.0;
						//用户直推
						if (null != commisConfig.getMerchantsCommission()) {
							ratio = commisConfig.getMerchantsCommission() / 100;
						}
						commission = order1.getPayprice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
						if (commission.compareTo(BigDecimal.ZERO) > 0) {
							OrderProduct orderProduct = new OrderProduct();
							if (list != null) {
								orderProduct = list.get(0);
							}
							commissionService.saveLog(new CommissionLog(referrerMember.getId(), orderId, orderProduct.getId(), CommissionLogType.MerchantsCommission.getType(),
									commission, referrerMember.getCentreId()));
						}
					}
				}

				//创建后台账户，并通知给用户
				//centreService.createAdminAccount(record);
			} else if (order1.getIsCentreUpgrade() != null && order1.getIsCentreUpgrade() == 1) {
				//升级为超级店主订单 状态变为已完成
				order1.setStatus(OrderStatus.success.getCode());
				//给用户添加超级店主角色
				MemberRole memberRole = new MemberRole();
				memberRole.setMemberId(order1.getMid());
				memberRole.setMemberRoleName(MemberRoleEnum.SUPER_SHOPKEEPER.getCode());
				memberRoleService.insert(memberRole);

				//查询相应的资产赠送额度
				AssetConfig assetConfig = configService.getAssetConfig(order1.getCentreId());
				//给用户添加资产
				Member member = new Member();
				member.setId(order1.getMid());
				MemberWallet memberWallet = memberWalletService.findById(member);
				if (memberWallet != null && null != assetConfig && assetConfig.getYearCombo() != null) {
					memberWallet.setAA(memberWallet.getAA().add(BigDecimal.valueOf(assetConfig.getYearCombo())));
					memberWalletService.update(memberWallet);
					//添加资产转入记录
					memberWalletService.insertLog(new MemberWalletLog(memberWallet.getEADD(), memberWallet.getMemberId(), WalletLogTypeEnum.AA.getCode(),
							WalletLogOperationTypeEnum.INCOME.getCode(), BigDecimal.valueOf(assetConfig.getYearCombo()), 100d));
				}

			} else if (order1.getIsStores() != null && order1.getIsStores() == 1) {
				//是门店申请 状态变为已完成
				order1.setStatus(OrderStatus.success.getCode());
				Member member = new Member();
				member.setId(order1.getMid());
				member.setPayStatus(PayStatus.PAY_SUCCESS.getCode());
				memberService.updateMemberAsync(member);
				logger.info("-------------------------------------修改信息" + JSON.toJSONString(member));
				//进行直推用户和代理商分佣
				//直推分佣
				Member memberResult = memberService.getByKey(order1.getMid());
				Member referrerMember = null;
				Long refMid = null;
				if (memberResult != null && memberResult.getUserid() != null) {
					referrerMember = memberService.getByKey(memberResult.getUserid());
					refMid = memberResult.getReferrerMid();
				}

				//门店推荐人分佣
				LifeConfig lifeConfig = configService.getLifeConfig(order1.getCentreId());
				if (lifeConfig != null && refMid != null) {
					//查询推荐人信息
					Member refMember = memberService.getByKey(refMid);
					String storesShareCommission = lifeConfig.getStoresShareCommission();
					if (ValidateUtil.isNotEmptyString(storesShareCommission) && !StringConstans.STR_ZERO.equals(storesShareCommission)) {
						boolean flag = memberService.commissionFlag(refMember, order1.getPortType());
						if (flag) {
							OrderProduct orderProduct = new OrderProduct();
							if (list != null) {
								orderProduct = list.get(0);
							}
							CommissionLog commissionLog = new CommissionLog();
							commissionLog.setMid(refMember.getUserid());
							commissionLog.setOrderId(order1.getId());
							commissionLog.setOrderProductId(orderProduct.getId());
							commissionLog.setType(CommissionLogType.storesShareCommission.getType());
							BigDecimal commission = order1.getPayprice().multiply(new BigDecimal(storesShareCommission)).divide(new BigDecimal(100), 2, RoundingMode.FLOOR);
							commissionLog.setCommission(commission);
							commissionLog.setCreateTime(new Date());
							commissionLog.setCentreId(order1.getCentreId());
							commissionService.saveLog(commissionLog);
						}
					}
				}

				if (referrerMember != null) {

					//获取佣金配置信息
					CommisConfig commisConfig = configService.getCommissionConfig(referrerMember.getCentreId());
					if (null != commisConfig) {
						//佣金
						BigDecimal commission = BigDecimal.ZERO;

						double ratio = 0.0;
						//用户直推
						if (null != commisConfig.getStoresCommission()) {
							ratio = commisConfig.getStoresCommission() / 100;
						}
						commission = order1.getPayprice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
						if (commission.compareTo(BigDecimal.ZERO) > 0) {
							OrderProduct orderProduct = new OrderProduct();
							if (list != null) {
								orderProduct = list.get(0);
							}
							commissionService.saveLog(new CommissionLog(referrerMember.getId(), orderId, orderProduct.getId(), CommissionLogType.StoresCommission.getType(),
									commission, referrerMember.getCentreId()));
						}
					}
				}

			} else if (order1.getOrderType() != null && order1.getOrderType() == ProductType.partner.getType()) {
				//合伙人套餐业务处理 状态变为已完成
				order1.setStatus(OrderStatus.success.getCode());
				//给用户添加合伙人角色
				MemberRole memberRole = new MemberRole();
				memberRole.setMemberId(order1.getMid());
				memberRole.setMemberRoleName(MemberRoleEnum.PARTNER.getCode());
				memberRoleService.insert(memberRole);

				//查询相应的资产赠送额度
				AssetConfig assetConfig = configService.getAssetConfig(order1.getCentreId());
				//给用户添加资产
				Member member = new Member();
				member.setId(order1.getMid());
				MemberWallet memberWallet = memberWalletService.findById(member);
				if (memberWallet != null && null != assetConfig && assetConfig.getPartnerCombo() != null) {
					memberWallet.setAA(memberWallet.getAA().add(BigDecimal.valueOf(assetConfig.getPartnerCombo())));
					memberWalletService.update(memberWallet);
					//添加资产转入记录
					memberWalletService.insertLog(new MemberWalletLog(memberWallet.getEADD(), memberWallet.getMemberId(), WalletLogTypeEnum.AA.getCode(),
							WalletLogOperationTypeEnum.INCOME.getCode(), BigDecimal.valueOf(assetConfig.getPartnerCombo()), 100d));
				}

				List<Member> memberList = memberService.getAllMember(null);
				//处理下级推荐的所属关系
				this.superiorRole(order1.getMid(), order1.getMid(), memberList, MemberRoleEnum.PARTNER.getCode());

			} else if (order1.getOrderType() != null && order1.getOrderType() == ProductType.FreeCharge.getType()) {
				order1.setStatus(OrderStatus.success.getCode());
			} else if (order1.getStatus() != OrderStatus.success.getCode()) {
				//不是站长支付商品 状态变为已发货
				order1.setStatus(OrderStatus.wait_send.getCode());
				//每下一个订单，生成对应的额度赠送记录---和众邦有关
//				memberGivenScoreService.givenQuota(orderId);
			}


			order1.setPaystatus(PayStatus.PAY_SUCCESS.getCode());
			//order1.setPaytype(PayType.WX_PAY);
			order1.setPayno(payNo);
			order1.setPayTime(now);
			if (procedureFee > 0) {
				order1.setYplProceduresAmount(BigDecimal.valueOf(procedureFee).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN));
			} else {
				order1.setYplProceduresAmount(BigDecimal.ZERO);
			}
			if (com.github.pagehelper.util.StringUtil.isNotEmpty(payChannel.getChannelCode()) && payChannel.getChannelCode().equals(PayChannelEnum.YPL.getCode())) {
				order1.setChanelcode(PayChannelEnum.YPL.getCode());
				order1.setChanelname(PayChannelEnum.YPL.getValue());
			}
//            if (order1.getOrderType().equals(6) && order1.getCateringType().equals(2)) {//外卖订单
			if (order1.getOrderType().equals(ProductType.WaiMai.getType())) {//外卖订单
				//预计送达时间
				Store store = storeService.getStoreByTeamid(order1.gettMid());
				if (store != null && StringUtils.isNotEmpty(store.getWaitTime())) {
					Calendar cal = Calendar.getInstance();
					cal.add(Calendar.MINUTE, Integer.parseInt(store.getWaitTime()));
					Date sendTime = cal.getTime();
					order1.setSendTime(sendTime);
				}
			}
			orderMapper.updateByPrimaryKeySelective(order1);
			//拼团订单业务处理
			if (order1.getOrderType() == ProductType.Spellgroup.getType()) {
				int result = verificationSpellGroup(order1);
				if (result < 0) {
					logger.info("拼团订单回掉修改人数失败");
				}
			}

			if (order1.getIsStores() != null && order1.getIsStores() == 1) {
				Member memberResult = memberService.getByKey(order1.getMid());
				//获取配置  判断是否需要审核
				TradeConfig tradeConfig = configService.getTradeConfig(memberResult.getCentreId());
				if (tradeConfig != null) {
					if (tradeConfig.getStoreAudit() == 1) {
						//不需要审核  直接调用审核接口通过审核
						memberResult.setIsteam(MemberType.COMMANDER.getCode());
						memberService.noCheckUpdate(memberResult);
					}
				}
			}


			//积分扣款
			integralService.consumerGrantIntegralNew2(order1);
		}
		if (deductPrice != null) {
			totalPayPrice = totalPayPrice.subtract(deductPrice);
		}
		Object obj = localRedis.get(CLOSED_ORDER.concat(orderId.toString()));
		if (obj != null) {
			order.setStatus(OrderStatus.cancel.getCode());
		}


		if (order.getStatus() != OrderStatus.wait_pay.getCode()) {
			if (OrderStatus.cancel.getCode() == order.getStatus()) {
				if (StringUtils.isNotEmpty(order.getPayno()) && order.getPayno().length() > 1) {
					logger.info("订单状态错误,重复支付回调，无法支付:{},orderId：{}", order.getStatus(), orderId);
					throw new BDException(BusinessCode.ORDER_PAYED_ERROR);
				} else {
					String refundNo = order.getOrdersn().concat("R");
					Map<String, Object> updMap = new HashMap<>();
					 {
						//订单状态已取消，
						logger.info("订单已取消,开始执行退款操作!");
						refundNo = order.getOutTradeNo().concat("DRC").concat(orderId.toString());
						try {
							WxPayRefundResult refund = myWxpayService.refund(payNo, null, refundNo, totalPayPrice.doubleValue(), order.getPayprice().doubleValue());
							if (refund == null) {
								logger.info("apply wx refund cant't get result!");
								return 0;
							}

							updMap.put("refundTime", new Date());
							updMap.put("refundNo", refund.getRefundId());
							updMap.put("refundsn", refund.getOutTradeNo());

						} catch (Exception e) {
							logger.info("微信退款失败,orderId:{},支付订单号:{},error:{}", orderId, payNo, e.getMessage());
						}
					}
					Payment payment = new Payment();
					payment.setPayTradeNo(order.getRefundNo());
					payment.setOutTradeNo(order.getOutTradeNo());
					payment.setOutRefundNo(refundNo);
					payment.setMoney(totalPayPrice);
					payment.setStatus(2);
					payment.setType("2");
					payment.setStyle(4);
					payment.setMid(order.getMid());
					payment.setTuikuantime(order.getRefundTime());
					payment.setTuikuanstatus(1);
					payment.setUpdateTime(new Date());
					paymentService.savePayment(payment);
					return orderMapper.updOrderPayAttach(updMap);

				}
			}
		}


		paymentService.savePayment(order);
		if (integral != null) {
			/*integralService.consumerIntegral(order.getMid(), integral, order.getOrdersn());*/
			//鲍凌宇-消费积分
			integralService.consumerGrantIntegralNew(order, integral);
			logger.info("integral consume success,mid:{},integral:{}", order.getMid(), integral);
		}

		return 1;
	}

	/**
	 * 优惠套餐回调处理
	 */
	private void packageCallback(Long orderId, Long mid, OrderProduct op, Order order1) {
		boolean orderStatusFinished = true;
		List<OrderProduct> orderProductList = orderProductMapper.getProductListByOrderId(orderId);
		if (ValidateUtil.isNotEmptyCollection(orderProductList)) {
			for (OrderProduct orderProductTemp : orderProductList) {
				ActivityProductExample example = new ActivityProductExample();
				example.createCriteria().andProductIdEqualTo(orderProductTemp.getProductId());
				List<ActivityProduct> activityProductList = activityProductMapper.selectByExample(example);
				if (ValidateUtil.isNotEmptyCollection(activityProductList)) {
					//判断订单状态是否是完成状态
					boolean isOrderProductStatusFinished = true;
					for (ActivityProduct activityProductTemp : activityProductList) {
						//优惠券套装的产品，订单状态直接不能设置为已完成，
						if (activityProductTemp.getType() == ActivityProductType.PACKAGE_PRODUCT.getType()) {
							isOrderProductStatusFinished = false;
						}
						//优惠券商品，将优惠券发给用户
						else {
							TicketRecord record = new TicketRecord();
							record.setMid(mid);
							record.setTicketId(activityProductTemp.getProductId());
							record.setNum(activityProductTemp.getStock());
							record.setIsFreeCharge(1);
							record.setOrderId(orderId);
							record.setTicketType(TicketRecordType.NORMAL.getType());
							ticketService.sendTicket(record);
						}
					}
					//优惠券套装的产品，订单状态直接设置为已完成，
					if (isOrderProductStatusFinished) {
						op.setStatus(OrderStatus.success.getCode());
					}
					//只要有一个是未完成，就设置为未完成
					else if (orderStatusFinished) {
						orderStatusFinished = false;
					}
				}
			}
		}
		if (orderStatusFinished) {
			order1.setStatus(OrderStatus.success.getCode());
		} else {
			//状态变为已发货
			op.setStatus(OrderStatus.wait_send.getCode());
		}
	}

	/**
	 * 免单活动回调处理
	 */
	private void freeChargeCallback(Long orderId, Order order, OrderProduct op, Order order1) {
		Member member = memberMapper.selectByPrimaryKey(order1.getMid());
		logger.info("====1===开始免单优惠券逻辑进入=========");
		List<OrderProduct> orderProductList = orderProductMapper.getProductListByOrderId(orderId);
		if (ValidateUtil.isNotEmptyCollection(orderProductList)) {
			logger.info("====2===orderProductList存在，循环处理=========");
			LifeConfig lifeConfig = configService.getLifeConfig(order.getCentreId());

			//查询商户信息
			Centre centre = centreService.getCentreById(order.getCentreId());
			//琰通商户信息
			Centre ytCentre = centreService.getCentreById(317L);
			//库表分账信息list
			List<OrderSplitInfo> orderSplitInfoList = new ArrayList<>();
			//易票联分账详细信息
			List<SplitInfo> splitInfoList = new ArrayList<>();
			//分账参数信息
			SplitRequest request = new SplitRequest();
			//琰通收取费率金额总和
			BigDecimal rateMoneyTotal = BigDecimal.ZERO;
			//发给门店的金额总和（需要加上琰通收取的费率后计算商户收的钱）
			BigDecimal teamMoneyTotal = BigDecimal.ZERO;

			for (OrderProduct orderProductTemp : orderProductList) {
				ActivityProductExample example = new ActivityProductExample();
				example.createCriteria().andActivityIdEqualTo(orderProductTemp.getProductId());
				List<ActivityProduct> activityProductList = activityProductMapper.selectByExample(example);
				logger.info("====3===activityProductList存在，循环处理======getProductId===" + orderProductTemp.getProductId());
				if (ValidateUtil.isNotEmptyCollection(activityProductList)) {
					Activity activity = activityMapper.selectByPrimaryKey(orderProductTemp.getProductId());

					for (ActivityProduct activityProductTemp : activityProductList) {
						logger.info("====4===循环出来的activityProductTemp存在======getProductId===" + activityProductTemp.getProductId());
						//免单产品，先赠送大礼包优惠券
						TicketRecord record = new TicketRecord();
						record.setMid(order.getMid());
						record.setTeamId(activityProductTemp.getProductId());
						record.setTicketId(0L);
						record.setNum(activityProductTemp.getStock());
						record.setTicketType(TicketRecordType.GIFT_PACKAGE.getType());//大礼包优惠券
						record.setGetTime(new Date());
						record.setStartTime(new Date());
						record.setOrderId(orderId);
//                                record.setEndTime(ticket.getEndTime());
						record.setCountUsed(0);
//                                record.setEndTime(DateUtils.getAddDayDate(now, ticket.getPeriod()));
						record.setNum(1);
						ticketRecordMapper.insertSelective(record);

						//门店ID
						Long shopMid = activityProductTemp.getProductId();
						if (null != shopMid) {
							List<StoreFreecharge> storeFreechargeList = null;
							List<String> list = new ArrayList<>();
							if (ValidateUtil.isNotEmptyString(activityProductTemp.getCouponIds())) {
								Collections.addAll(list, activityProductTemp.getCouponIds().split(","));
								storeFreechargeList = storeFreechargeMapper.selectByIdInStoreFreecharge(list);
							}
							if (storeFreechargeList != null) {
								//循环优惠券列表，将优惠券每张都发给用户，并且，parentID设置为上面插入的记录
								for (StoreFreecharge storeFreechargeInfo : storeFreechargeList) {
									Ticket ticket = ticketService.getByKey(storeFreechargeInfo.getRefId());

									TicketRecord recordStore = new TicketRecord();
									recordStore.setMid(order.getMid());
									recordStore.setTicketId(storeFreechargeInfo.getRefId());
//									recordStore.setNum(storeFreechargeInfo.getCount() == null || storeFreechargeInfo.getCount() == 0 ? 1 : storeFreechargeInfo.getCount());
									recordStore.setNum(1);

									if (ticket.getUsableFlag() != null && ticket.getUsableFlag() == 0) {
										recordStore.setTeamId(storeFreechargeInfo.getTeamId());
									} else {
										//查询订单用户选择的通兑券门店
										UsableTeamMiddle usableTeamMiddle = usableTeamMiddleMapper.selectByOrderIdAndTicketId(orderId, ticket.getId());
										if (usableTeamMiddle != null) {
											recordStore.setTeamId(usableTeamMiddle.getTeamId());
										} else {
											recordStore.setTeamId(storeFreechargeInfo.getTeamId());
										}
									}

									recordStore.setOrderId(orderId);
									recordStore.setParentId(record.getParentId());
									recordStore.setIsFreeCharge(1);
									//礼包子优惠券
									recordStore.setTicketType(TicketRecordType.GIFT_PACKAGE_SUB.getType());

									ticketService.sendTicket(recordStore);

									//同时需要处理分账信息，存入t_order_split_info表，在用户支付后门店可以统计到各项数据
									BigDecimal commissionTotal = BigDecimal.ZERO;
									String commissionIds = "";

									SplitInfo splitInfo = null;
									OrderSplitInfo orderSplitInfo = null;
//									if (ProductType.FreeCharge.getType() == order.getOrderType() && BigDecimal.ZERO.compareTo(ticket.getBigGiftAmount()) == 0) {
									if (ProductType.FreeCharge.getType() == order.getOrderType()) {
										//计算易票联交易手续费和琰通收取的服务费
										//查询优惠券所属的门店
										Member collectionMember = memberService.getByKey(recordStore.getTeamId());
										//线上费率
										Double deductionRatio = centre.getDeductionRatio();
										BigDecimal deductionMoney = ticket.getBigGiftAmount().multiply(BigDecimal.valueOf(deductionRatio / 100)).setScale(2, RoundingMode.DOWN);
										//计算琰通总收取的费率金额
										rateMoneyTotal = rateMoneyTotal.add(deductionMoney);

										//优惠券核销价格减去总佣金减去琰通扣点减去易票联交易手续费等于门店实际所得金额
										BigDecimal teamMoney = ticket.getBigGiftAmount().subtract(commissionTotal).subtract(deductionMoney);

										//构建表信息
										orderSplitInfo = new OrderSplitInfo();
										orderSplitInfo.setOrderId(order.getId());
										orderSplitInfo.setOrderProductId(orderProductTemp.getId());
										orderSplitInfo.setRefId(ticket.getId());
										orderSplitInfo.setOutTradeNo(order.getOutTradeNo());
										orderSplitInfo.setType(1);
										orderSplitInfo.setSplitType(1);
										orderSplitInfo.setMoney(teamMoney);
										orderSplitInfo.setServiceCharge(deductionMoney);
										orderSplitInfo.setServiceChargeRate(BigDecimal.valueOf(deductionRatio));
										orderSplitInfo.setCommissionTotal(commissionTotal);
										orderSplitInfo.setCommission(ValidateUtil.isEmptyString(commissionIds) ? null : commissionIds.substring(0, commissionIds.length() - 1));
										orderSplitInfo.setCentreId(collectionMember.getCentreId());
										orderSplitInfo.setTeamId(collectionMember.getId());
										orderSplitInfo.setStatus(0);
										orderSplitInfo.setPayMid(order.getMid());

										 {
											orderSplitInfo.setRemark("大礼包付款，门店无法分账收款，金额分账到商户账户中，给门店发放虚拟余额");
											if (order.getPaytype() == 1) {
												teamMoneyTotal = teamMoneyTotal.add(teamMoney);
												orderSplitInfo.setRemark("大礼包付款，给门店发放虚拟余额");
											}
											if (collectionMember.getIsHeadOffice() != 1) {
												//加入用户未结算余额
												Member member1 = new Member();
												member1.setId(collectionMember.getId());
												member1.setNoSettlementCredit2(collectionMember.getNoSettlementCredit2().add(teamMoney));
												memberService.updateMemberAsync(member1);

											}
										}
										orderSplitInfoList.add(orderSplitInfo);
									}
									if (splitInfo != null) {
										splitInfoList.add(splitInfo);
									}
								}
							}
						}
					}

					//分佣
					if (ProductType.FreeCharge.getType() == order.getOrderType()) {
						String shareCommission = "";
						//大礼包分享人佣金，得先查询大礼包是否设置分佣，如果大礼包没有设置则取平台设置中的比例
						if (activity.getShareCommission() > 0) {
							shareCommission = activity.getShareCommission() + "";
						} else {
							shareCommission = lifeConfig.getShareCommission();
						}
						if (order.getShareMid() != null && ValidateUtil.isNotEmptyString(shareCommission) && !StringConstans.STR_ZERO.equals(shareCommission)) {
							Member shareMember = memberMapper.selectByPrimaryKey(order.getShareMid());
							boolean flag = memberService.commissionFlag(shareMember, order.getPortType());
							if (flag) {
								BigDecimal commission = order.getPayprice().multiply(new BigDecimal(shareCommission)).divide(new BigDecimal(100), 2, RoundingMode.DOWN);
								if (BigDecimal.ZERO.compareTo(commission) < 0) {
									CommissionLog commissionLog = new CommissionLog();
									commissionLog.setMid(order.getShareMid());
									commissionLog.setOrderId(order.getId());
									commissionLog.setOrderProductId(orderProductTemp.getId());
									commissionLog.setType(CommissionLogType.freePackageCommissionShare.getType());
									commissionLog.setCommission(commission);
									commissionLog.setCreateTime(new Date());
									commissionLog.setCentreId(order.getCentreId());
									//commissionLog.setTicketId(ticket.getId());
									commissionService.saveLog(commissionLog);
								}
							}
						}
					}
					if (op != null) {
						op.setStatus(OrderStatus.success.getCode());
					}
				}
			}

			if (ProductType.FreeCharge.getType() == order.getOrderType()) {
				if (BigDecimal.ZERO.compareTo(rateMoneyTotal) < 0) {
					OrderSplitInfo orderSplitInfo1 = new OrderSplitInfo();
					orderSplitInfo1.setOrderId(order.getId());
					orderSplitInfo1.setOutTradeNo(order.getOutTradeNo());
					orderSplitInfo1.setType(1);
					orderSplitInfo1.setPayMid(order.getMid());
					if (order.getPaytype() != 1) {
						orderSplitInfo1.setSplitType(2);
						splitInfoList.add(new SplitInfo(ytCentre.getYplCustomerCode(), rateMoneyTotal.multiply(new BigDecimal("100")).longValue(), 0));
					} else {
						orderSplitInfo1.setSplitType(1);
					}
					orderSplitInfo1.setMoney(rateMoneyTotal);
					orderSplitInfo1.setCustomerCode(ytCentre.getYplCustomerCode());
					orderSplitInfo1.setCentreId(ytCentre.getCentreId());
					orderSplitInfo1.setStatus(1);
					orderSplitInfo1.setStatusTime(new Date());
					orderSplitInfo1.setCommissionTotal(BigDecimal.ZERO);
					orderSplitInfo1.setServiceCharge(BigDecimal.ZERO);
					orderSplitInfo1.setServiceChargeRate(BigDecimal.ZERO);
					orderSplitInfo1.setRemark("大礼包付款，琰通收取的服务费");
					orderSplitInfoList.add(orderSplitInfo1);
				}
				BigDecimal centreMoneyTotal = order.getPayprice().subtract(teamMoneyTotal).subtract(rateMoneyTotal);
				if (BigDecimal.ZERO.compareTo(centreMoneyTotal) < 0) {
					OrderSplitInfo orderSplitInfo1 = new OrderSplitInfo();
					orderSplitInfo1.setOrderId(order.getId());
					orderSplitInfo1.setYfzServiceChargeFlag(1);
					orderSplitInfo1.setOutTradeNo(order.getOutTradeNo());
					orderSplitInfo1.setType(1);
					orderSplitInfo1.setPayMid(order.getMid());
					if (order.getPaytype() != 1) {
						orderSplitInfo1.setSplitType(2);
						splitInfoList.add(new SplitInfo(centre.getYplCustomerCode(), centreMoneyTotal.multiply(new BigDecimal("100")).longValue(), 3));
					} else {
						orderSplitInfo1.setSplitType(1);
					}
					orderSplitInfo1.setMoney(centreMoneyTotal);
					orderSplitInfo1.setCustomerCode(centre.getYplCustomerCode());
					orderSplitInfo1.setCentreId(centre.getCentreId());
					orderSplitInfo1.setStatus(1);
					orderSplitInfo1.setStatusTime(new Date());
					orderSplitInfo1.setCommissionTotal(BigDecimal.ZERO);
					orderSplitInfo1.setServiceCharge(BigDecimal.ZERO);
					orderSplitInfo1.setServiceChargeRate(BigDecimal.ZERO);
					orderSplitInfo1.setRemark("大礼包付款，商户收取的费用（佣金，门店无法收取的分账金额等）");
					orderSplitInfoList.add(orderSplitInfo1);
				}

				//将分账信息存入库表
				if (ValidateUtil.isNotEmptyCollection(orderSplitInfoList)) {
					logger.info("orderSplitInfo表存储信息：" + JSONObject.toJSONString(orderSplitInfoList));
					if (ValidateUtil.isNotEmptyCollection(splitInfoList)) {
						//合并重复项  否则易票联分账会报错（重复分账）
						splitInfoList = this.mergeSplitInfoList(splitInfoList);
						for (OrderSplitInfo orderSplitInfo : orderSplitInfoList) {
							orderSplitInfo.setSplitResultInfoList(JSONObject.toJSONString(splitInfoList));
						}
					}
					orderSplitInfoMapper.insertList(orderSplitInfoList);
				}

				logger.error("大礼包分账详细信息：" + JSONObject.toJSONString(splitInfoList));
				//大礼包没有退款流程   所以直接先走易票联的延迟分账
				if (ValidateUtil.isNotEmptyCollection(splitInfoList)) {
					request.setOutTradeNo(order.getOutTradeNo());
					request.setCustomerCode(centre.getYplCustomerCode());
					request.setSplitInfoList(splitInfoList);
					request.setNotifyUrl(templatemsgCreateUserUrl + "/notify/yfz/split/call-back");
					try {
						SplitResponse splitResponse = YFZPayutil.split(centre, request);
						orderSplitInfoMapper.updateByOutTradeNoReturn(order.getOutTradeNo(), splitResponse.getReturnCode(), splitResponse.getReturnMsg());
						logger.error("大礼包分账返回信息：" + JSONObject.toJSONString(splitResponse));
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}

			}
		}
		Order orderParam = new Order();
		orderParam.setId(order1.getId());
		orderParam.setStatus(OrderStatus.success.getCode());
		orderMapper.updateByPrimaryKeySelective(orderParam);
		OrderProduct record = new OrderProduct();
		record.setOrderid(order1.getId());
		record.setStatus(OrderStatus.success.getCode());
		orderProductMapper.updateByParam(record);

		if (ValidateUtil.isNotEmptyString(member.getOpenid())) {
			/*
			{{first.DATA}}
			订单商品：{{keyword1.DATA}}
			订单编号：{{keyword2.DATA}}
			订单金额：{{keyword3.DATA}}
			支付时间：{{keyword4.DATA}}
			{{remark.DATA}}
			 */
			String firstString = "购买成功！";
			String productName = null;
			if (ValidateUtil.isNotEmptyCollection(orderProductList)) {
				int productNum = orderProductList.size();
				productName = StringConstans.STR_EMPTY;
				if (productNum == 1) {
					productName = orderProductList.get(0).getProductName();
				}
				if (productNum > 1) {
					productName = orderProductList.get(0).getProductName() + "等" + productNum + "件";
				}
				firstString = productName + firstString;
			}
			Map<String, String> map = new HashMap<>();
			String url = null;
			url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/index.html";
			map.put("firstString", firstString);
			map.put("productName", productName);
			map.put("ordersn", order.getOrdersn());
			map.put("payprice", order.getPayprice() + StringConstans.STR_EMPTY);
			map.put("paytime", DateUtil.convertDateToStr(new Date(), DateUtil.yyyy_MM_dd_HH_mm_ss));
			map.put("remarkrest", "点击页面查看详情");
			orderService.sendGZHProductGeneralMsg(member.getCentreId(), member.getId(), map, url);
		}

		if (member.getCentreId().equals(317L) && null != member && member.getIsVip() != 1) {
			member.setIsVip(1);
			member.setVipTime(new Date());
			//琰通购买大礼包赠送一个季度的王权会员
			member.setVipEndTime(DateUtils.getAddMonthDate(new Date(), 3));
			memberMapper.updateByPrimaryKey(member);
		}
	}
	/**
	 *  根据订单地区或者注册关系查找代理并添加佣金记录
	 *
	 * @author huangshuai
	 * @date 2021/1/22 10:30
	 */
	@Override
	public void calculateCommissionByOrderArea(Long mid, Long orderId, Long orderProductId, BigDecimal orderMoney) {

		//获取对应订单
		Order order = orderMapper.selectByPrimaryKey(orderId);
		//下单用户
		Member orderMember = memberService.getByKey(order.getMid());
		//获取配置用户代理计算规则
		CommisConfig useragentCountRuleTypeConfig = configService.getCommissionConfig(orderMember.getCentreId());
		if (useragentCountRuleTypeConfig.getUseragentCountRuleType() != null) {
			//throw new BDException("未设置用户代理计算规则");
			if (useragentCountRuleTypeConfig.getUseragentCountRuleType() == 0) {   //如果以注册关系为准分发代理佣金

			} else if (useragentCountRuleTypeConfig.getUseragentCountRuleType() == 1) { //如果按区域分发佣金为准
				MemberUseragent memberUseragentArea = memberUseragentMapper.selectByArea(order.getDistrict());
				MemberUseragent memberUseragentCity = memberUseragentMapper.selectByCity(order.getCity());
				MemberUseragent memberUseragentProvince = memberUseragentMapper.selectByProvince(order.getProvince());
				MemberUseragent memberUseragent = new MemberUseragent();
				if (memberUseragentArea != null) {
					BeanUtils.copyProperties(memberUseragentArea, memberUseragent);
				} else if (memberUseragentCity != null) {
					BeanUtils.copyProperties(memberUseragentCity, memberUseragent);
				} else if (memberUseragentProvince != null) {
					BeanUtils.copyProperties(memberUseragentProvince, memberUseragent);
				}
				//查询代理用户信息
				if (memberUseragent != null) {
					Member Useragent = memberService.getByKey(memberUseragent.getMemberId());
					if (Useragent != null) {
						//获取佣金配置信息
						//CommisConfig commisConfig = configService.getCommissionConfig(Useragent.getCentreId());
						if (null != useragentCountRuleTypeConfig) {
							//佣金
							BigDecimal commission1 = BigDecimal.ZERO;
							double ratio = 0.0;
							//代理人佣金比例
							if (null != useragentCountRuleTypeConfig.getAgentcommission()) {
								ratio = useragentCountRuleTypeConfig.getAgentcommission() / 100;
							}
							commission1 = orderMoney.multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
							if (commission1.compareTo(BigDecimal.ZERO) > 0) {
								commissionService.saveLog(new CommissionLog(Useragent.getId(), orderId, orderProductId, CommissionLogType.userAgent.getType(),
										commission1, Useragent.getCentreId()));
							}
						}
					}
//					else {
//						throw new BDException("代理人信息不存在！");
//					}
				}
				//获取推荐代理人信息
				if (memberUseragent.getReferenceId() != null && !memberUseragent.getReferenceId().equals("")) {
					Member memberReference = memberService.getByKey(memberUseragent.getReferenceId());
					//获取佣金配置信息
					//CommisConfig commisConfig = configService.getCommissionConfig(memberReference.getCentreId());
					if (null != useragentCountRuleTypeConfig) {
						//佣金
						BigDecimal commission1 = BigDecimal.ZERO;
						double ratio = 0.0;
						//推荐代理人佣金比例
						if (null != useragentCountRuleTypeConfig.getUseragentCommission()) {
							ratio = useragentCountRuleTypeConfig.getUseragentCommission() / 100;
						}
						commission1 = orderMoney.multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
						if (commission1.compareTo(BigDecimal.ZERO) > 0) {
							commissionService.saveLog(new CommissionLog(memberReference.getId(), orderId, orderProductId, CommissionLogType.referenceUserAgent.getType(),
									commission1, memberReference.getCentreId()));
						}
					}
				}
			}
		}
	}


	/**
	 * 计算佣金并添加佣金记录信息
	 */
	@Override
	public void calculateCommission(Long mid, Long orderId, Long orderProductId, BigDecimal orderMoney, Long centreId) {
		//查询用户信息
		Member member = memberService.getByKey(mid);
		Member referrerMember = null;
		if (member != null && member.getUserid() != null) {
			referrerMember = memberService.getByKey(member.getUserid());
		}

		if (referrerMember != null) {
			//查询推荐人的角色信息
			List<String> listRole = memberRoleService.queryList(referrerMember.getId());
			//获取佣金配置信息
			CommisConfig commisConfig = configService.getCommissionConfig(referrerMember.getCentreId());
			if (null != commisConfig) {
				//佣金
				BigDecimal commission1 = BigDecimal.ZERO;
				BigDecimal commission2 = BigDecimal.ZERO;
				BigDecimal commission3 = BigDecimal.ZERO;
				BigDecimal commission4 = BigDecimal.ZERO;
				BigDecimal commission5 = BigDecimal.ZERO;
				BigDecimal commission;

				double ratio = 0.0;
				//推客直推
				if (listRole.contains(MemberRoleEnum.TWITTER.getCode())) {
					if (null != commisConfig.getTwitterCommission()) {
						ratio = commisConfig.getTwitterCommission() / 100;
					}
					commission1 = orderMoney.multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
					if (commission1.compareTo(BigDecimal.ZERO) > 0) {
						commissionService.saveLog(new CommissionLog(referrerMember.getId(), orderId, orderProductId, CommissionLogType.TwitterCommission.getType(),
								commission1, centreId));
					}
				}
				//管家直推
				else if (listRole.contains(MemberRoleEnum.HOUSEKEEPER.getCode())) {
					if (null != commisConfig.getHousekeeperCommission()) {
						ratio = commisConfig.getHousekeeperCommission() / 100;
					}
					commission1 = orderMoney.multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
					if (commission1.compareTo(BigDecimal.ZERO) > 0) {
						commissionService.saveLog(new CommissionLog(referrerMember.getId(), orderId, orderProductId, CommissionLogType.HousekeeperCommission.getType(),
								commission1, centreId));
					}
				}
				//主管直推
				else if (listRole.contains(MemberRoleEnum.SUPERVISOR.getCode())) {
					if (null != commisConfig.getSupervisorCommission()) {
						ratio = commisConfig.getSupervisorCommission() / 100;
					}
					commission1 = orderMoney.multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
					if (commission1.compareTo(BigDecimal.ZERO) > 0) {
						commissionService.saveLog(new CommissionLog(referrerMember.getId(), orderId, orderProductId, CommissionLogType.SupervisorCommission.getType(),
								commission1, centreId));
					}
				}

				//超级店主直推(超级店主的前提是必须为店主，如店主过期则不能享受超级店主权益)
				if (listRole.contains(MemberRoleEnum.SUPER_SHOPKEEPER.getCode()) && referrerMember.getIsCentre() == 1) {
					if (null != commisConfig.getSuperShopkeeperCommission()) {
						ratio = commisConfig.getSuperShopkeeperCommission() / 100;
					}
					commission2 = orderMoney.multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
					if (commission2.compareTo(BigDecimal.ZERO) > 0) {
						commissionService.saveLog(new CommissionLog(referrerMember.getId(), orderId, orderProductId, CommissionLogType.SuperShopkeeperCommission.getType(),
								commission2, centreId));
					}
				}

				//合伙人直推
				if (listRole.contains(MemberRoleEnum.PARTNER.getCode())) {
					if (null != commisConfig.getPartnerCommission()) {
						ratio = commisConfig.getPartnerCommission() / 100;
					}
					commission = orderMoney.multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
					if (commission.compareTo(BigDecimal.ZERO) > 0) {
						commissionService.saveLog(new CommissionLog(referrerMember.getId(), orderId, orderProductId, CommissionLogType.PartnerCommission.getType(),
								commission, centreId));
					}
				}

			}
		}
	}

	@Override
	public void marketingGroupCommission(Order order) {
		logger.info("佣金发放开始");
		//通过订单id查询订单商品列表
		List<OrderProduct> orderProductList = orderProductMapper.getByOrderId(order.getId());
		for (OrderProduct orderProduct : orderProductList) {
			//用户信息
			Member member = memberService.getByKey(orderProduct.getMid());

			//查询商户信息
			Centre centre = centreService.getCentreById(order.getCentreId());
			//琰通商户信息
			Centre ytCentre = centreService.getCentreById(317L);
			//库表分账信息list
			List<OrderSplitInfo> orderSplitInfoList = new ArrayList<>();
			//易票联分账详细信息
			List<SplitInfo> splitInfoList = new ArrayList<>();
			//分账参数信息
			SplitRequest request = new SplitRequest();
			//琰通收取费率金额总和
			BigDecimal rateMoneyTotal = BigDecimal.ZERO;
			//发给门店的金额总和（需要加上琰通收取的费率后计算商户收的钱）
			BigDecimal teamMoneyTotal = BigDecimal.ZERO;

			//查询拼团活动信息
			MarketingGroup marketingGroup = marketingGroupMapper.getMarketingGroupById(orderProduct.getActivityId());
			if (MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(marketingGroup.getMarketingGroupType())) {
				ActivityProductExample example = new ActivityProductExample();
				example.createCriteria().andActivityIdEqualTo(orderProduct.getProductId());
				List<ActivityProduct> activityProductList = activityProductMapper.selectByExample(example);
				if (ValidateUtil.isNotEmptyCollection(activityProductList)) {
					for (ActivityProduct activityProductTemp : activityProductList) {
						//门店ID
						Long shopMid = activityProductTemp.getProductId();
						if (null != shopMid) {
							List<StoreFreecharge> storeFreechargeList = null;
							List<String> list = new ArrayList<>();
							if (ValidateUtil.isNotEmptyString(activityProductTemp.getCouponIds())) {
								Collections.addAll(list, activityProductTemp.getCouponIds().split(","));
								storeFreechargeList = storeFreechargeMapper.selectByIdInStoreFreecharge(list);
							}
							if (storeFreechargeList != null) {
								//循环优惠券列表，将优惠券每张都发给用户，并且，parentID设置为上面插入的记录
								for (StoreFreecharge storeFreechargeInfo : storeFreechargeList) {
									Ticket ticket = ticketService.getByKey(storeFreechargeInfo.getRefId());

									if (ticket.getUsableFlag() != null && ticket.getUsableFlag() == 1) {
										//查询订单用户选择的通兑券门店
										UsableTeamMiddle usableTeamMiddle = usableTeamMiddleMapper.selectByOrderIdAndTicketId(order.getId(), ticket.getId());
										if (usableTeamMiddle != null) {
											ticket.setTeamId(usableTeamMiddle.getTeamId());
										}
									}

									//同时需要处理分账信息，存入t_order_split_info表，在用户支付后门店可以统计到各项数据
									BigDecimal commissionTotal = BigDecimal.ZERO;
									String commissionIds = "";
									SplitInfo splitInfo = null;
									OrderSplitInfo orderSplitInfo = null;

//									if (BigDecimal.ZERO.compareTo(ticket.getBigGiftAmount()) == 0) {
									 {
										//计算易票联交易手续费和琰通收取的服务费
										//查询优惠券所属的门店
										Member collectionMember = memberService.getByKey(ticket.getTeamId());
										//线上费率
										Double deductionRatio = centre.getDeductionRatio();
										BigDecimal deductionMoney = ticket.getBigGiftAmount().multiply(BigDecimal.valueOf(deductionRatio / 100)).setScale(2, RoundingMode.DOWN);
										//计算琰通总收取的费率金额
										rateMoneyTotal = rateMoneyTotal.add(deductionMoney);

										//优惠券核销价格减去总佣金减去琰通扣点减去易票联交易手续费等于门店实际所得金额
										BigDecimal teamMoney = ticket.getBigGiftAmount().subtract(commissionTotal).subtract(deductionMoney);

										//构建表信息
										orderSplitInfo = new OrderSplitInfo();
										orderSplitInfo.setOrderId(order.getId());
										orderSplitInfo.setOrderProductId(orderProduct.getId());
										orderSplitInfo.setRefId(ticket.getId());
										orderSplitInfo.setOutTradeNo(order.getOutTradeNo());
										orderSplitInfo.setType(1);
										orderSplitInfo.setSplitType(1);
										orderSplitInfo.setMoney(teamMoney);
										orderSplitInfo.setServiceCharge(deductionMoney);
										orderSplitInfo.setServiceChargeRate(BigDecimal.valueOf(deductionRatio));
										orderSplitInfo.setCommissionTotal(commissionTotal);
										orderSplitInfo.setCommission(ValidateUtil.isEmptyString(commissionIds) ? null : commissionIds.substring(0, commissionIds.length() - 1));
										orderSplitInfo.setCentreId(collectionMember.getCentreId());
										orderSplitInfo.setTeamId(collectionMember.getId());
										orderSplitInfo.setStatus(0);
										orderSplitInfo.setPayMid(order.getMid());

										//不是商户下的直属门店
										 {
											orderSplitInfo.setRemark("大礼包拼团支付，门店无法分账收款，金额分账到商户账户中，给门店发放虚拟余额");
											if (order.getPaytype() == 1) {
												teamMoneyTotal = teamMoneyTotal.add(teamMoney);
												orderSplitInfo.setRemark("大礼包拼团支付，给门店发放虚拟余额");
											}
											if (collectionMember.getIsHeadOffice() != 1) {
												//加入用户未结算余额
												Member member1 = new Member();
												member1.setId(collectionMember.getId());
												member1.setNoSettlementCredit2(collectionMember.getNoSettlementCredit2().add(teamMoney));
												memberService.updateMemberAsync(member1);

											}
										}
										orderSplitInfoList.add(orderSplitInfo);

										if (splitInfo != null) {
											splitInfoList.add(splitInfo);
										}
									}
								}

								Double oneCommission = marketingGroup.getOneCommission();
								//拼团订单一级推荐人分佣
								if (oneCommission != null && oneCommission > 0 && member.getUserid() != null) {
									Member memberResult = memberMapper.selectByPrimaryKey(member.getUserid());
									boolean flag = memberService.commissionFlag(memberResult, order.getPortType());
									if (flag) {
										double ratio = oneCommission / 100;
										BigDecimal commissionOne = order.getPayprice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
										if (commissionOne.compareTo(BigDecimal.ZERO) > 0) {
											logger.info("拼团订单一级推荐人分佣----" + commissionOne);
											CommissionLog commissionLog = new CommissionLog(member.getUserid(), order.getId(), orderProduct.getId(), CommissionLogType.GroupCommissionOne.getType(),
													commissionOne, member.getCentreId(), null);
											commissionService.saveLog(commissionLog);
										}
									}
								}

								//拼团订单二级推荐人分佣
								Double twoCommission = marketingGroup.getTwoCommission();
								if (twoCommission != null && twoCommission > 0 && member.getUpUserid() != null) {
									Member memberResult = memberMapper.selectByPrimaryKey(member.getUpUserid());
									boolean flag = memberService.commissionFlag(memberResult, order.getPortType());
									if (flag) {
										double ratio = twoCommission / 100;
										BigDecimal commissionTwo = order.getPayprice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
										if (commissionTwo.compareTo(BigDecimal.ZERO) > 0) {
											logger.info("拼团订单二级推荐人分佣----" + commissionTwo);
											CommissionLog commissionLog = new CommissionLog(member.getUpUserid(), order.getId(), orderProduct.getId(), CommissionLogType.GroupCommissionTwo.getType(),
													commissionTwo, member.getCentreId(), null);
											commissionService.saveLog(commissionLog);
										}
									}
								}

								//拼团发起人分佣
								Double sponsorCommission = marketingGroup.getInitiatorCommission();
								if (sponsorCommission != null && sponsorCommission > 0 && order.getSgorderId() != null) {
//									if (sponsorCommission != null && sponsorCommission > 0 && order.getSgorderId() != null && !order.getSgorderId().equals(order.getId())) {
									Order orderResult = orderMapper.selectByPrimaryKey(order.getSgorderId());
									if (orderResult != null) {
										Member memberResult = memberMapper.selectByPrimaryKey(orderResult.getMid());
										boolean flag = memberService.commissionFlag(memberResult, order.getPortType());
										if (!flag) {
											sponsorCommission = marketingGroup.getGeneralMemberCommission();
										}
										double ratio = sponsorCommission / 100;
										BigDecimal commissionSponsor = order.getPayprice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
										if (commissionSponsor.compareTo(BigDecimal.ZERO) > 0) {
											logger.info("拼团发起人分佣----" + commissionSponsor);
											CommissionLog commissionLog = new CommissionLog(orderResult.getMid(), order.getId(), orderProduct.getId(), CommissionLogType.GroupCommissionSponsor.getType(),
													commissionSponsor, orderResult.getCentreId(), null);
											commissionService.saveLog(commissionLog);
										}
									}
								}
							}
						}
					}
				}

				if (BigDecimal.ZERO.compareTo(rateMoneyTotal) < 0) {
					OrderSplitInfo orderSplitInfo = new OrderSplitInfo();
					orderSplitInfo.setOrderId(order.getId());
					orderSplitInfo.setOutTradeNo(order.getOutTradeNo());
					orderSplitInfo.setType(1);
					if (order.getPaytype() != 1) {
						orderSplitInfo.setSplitType(2);
						splitInfoList.add(new SplitInfo(ytCentre.getYplCustomerCode(), rateMoneyTotal.multiply(new BigDecimal("100")).longValue(), 0));
					} else {
						orderSplitInfo.setSplitType(1);
					}
					orderSplitInfo.setMoney(rateMoneyTotal);
					orderSplitInfo.setCustomerCode(ytCentre.getYplCustomerCode());
					orderSplitInfo.setCentreId(ytCentre.getCentreId());
					orderSplitInfo.setStatus(1);
					orderSplitInfo.setStatusTime(new Date());
					orderSplitInfo.setPayMid(order.getMid());
					orderSplitInfo.setCommissionTotal(BigDecimal.ZERO);
					orderSplitInfo.setServiceCharge(BigDecimal.ZERO);
					orderSplitInfo.setServiceChargeRate(BigDecimal.ZERO);
					orderSplitInfo.setRemark("大礼包拼团支付，琰通收取的服务费");
					orderSplitInfoList.add(orderSplitInfo);
				}
				BigDecimal centreMoneyTotal = order.getPayprice().subtract(teamMoneyTotal).subtract(rateMoneyTotal);
				if (BigDecimal.ZERO.compareTo(centreMoneyTotal) < 0) {
					OrderSplitInfo orderSplitInfo = new OrderSplitInfo();
					orderSplitInfo.setOrderId(order.getId());
					orderSplitInfo.setOutTradeNo(order.getOutTradeNo());
					orderSplitInfo.setType(1);
					orderSplitInfo.setYfzServiceChargeFlag(1);
					orderSplitInfo.setPayMid(order.getMid());
					if (order.getPaytype() != 1) {
						orderSplitInfo.setSplitType(2);
						splitInfoList.add(new SplitInfo(centre.getYplCustomerCode(), centreMoneyTotal.multiply(new BigDecimal("100")).longValue(), 3));
					} else {
						orderSplitInfo.setSplitType(1);
					}
					orderSplitInfo.setMoney(centreMoneyTotal);
					orderSplitInfo.setCustomerCode(centre.getYplCustomerCode());
					orderSplitInfo.setCentreId(centre.getCentreId());
					orderSplitInfo.setStatus(1);
					orderSplitInfo.setStatusTime(new Date());
					orderSplitInfo.setCommissionTotal(BigDecimal.ZERO);
					orderSplitInfo.setServiceCharge(BigDecimal.ZERO);
					orderSplitInfo.setServiceChargeRate(BigDecimal.ZERO);
					orderSplitInfo.setRemark("大礼包拼团支付，商户收取的费用（佣金，门店无法收取的分账金额等）");
					orderSplitInfoList.add(orderSplitInfo);
				}

				//将分账信息存入库表
				if (ValidateUtil.isNotEmptyCollection(orderSplitInfoList)) {
					logger.error("orderSplitInfo表存储信息：" + JSONObject.toJSONString(orderSplitInfoList));
					if (ValidateUtil.isNotEmptyCollection(splitInfoList)) {
						//合并重复项  否则易票联分账会报错（重复分账）
						splitInfoList = this.mergeSplitInfoList(splitInfoList);
						for (OrderSplitInfo orderSplitInfo : orderSplitInfoList) {
							orderSplitInfo.setSplitResultInfoList(JSONObject.toJSONString(splitInfoList));
						}
					}
					orderSplitInfoMapper.insertList(orderSplitInfoList);
				}

				logger.error("大礼包分账详细信息：" + JSONObject.toJSONString(splitInfoList));
				//拼团没有退款流程   所以直接先走易票联的延迟分账
				if (ValidateUtil.isNotEmptyCollection(splitInfoList)) {
					request.setOutTradeNo(order.getOutTradeNo());
					request.setCustomerCode(centre.getYplCustomerCode());
					request.setSplitInfoList(splitInfoList);
					request.setNotifyUrl(templatemsgCreateUserUrl + "/notify/yfz/split/call-back");
					try {
						SplitResponse splitResponse = YFZPayutil.split(centre, request);
						orderSplitInfoMapper.updateByOutTradeNoReturn(order.getOutTradeNo(), splitResponse.getReturnCode(), splitResponse.getReturnMsg());
						logger.error("大礼包分账返回信息：" + JSONObject.toJSONString(splitResponse));
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}

			} else {
				//同时需要处理分账信息，存入t_order_split_info表，在用户支付后门店可以统计到各项数据
				BigDecimal commissionTotal = BigDecimal.ZERO;
				String commissionIds = "";
				SplitInfo splitInfo = null;
				OrderSplitInfo orderSplitInfo = null;

				Double oneCommission = marketingGroup.getOneCommission();
				//拼团订单一级推荐人分佣
				if (oneCommission != null && oneCommission > 0 && member.getUserid() != null) {
					Member memberResult = memberMapper.selectByPrimaryKey(member.getUserid());
					boolean flag = memberService.commissionFlag(memberResult, order.getPortType());
					if (flag) {
						double ratio = oneCommission / 100;
						BigDecimal commissionOne = order.getPayprice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
						if (commissionOne.compareTo(BigDecimal.ZERO) > 0) {
							commissionTotal = commissionTotal.add(commissionOne);
							logger.info("拼团订单一级推荐人分佣----" + commissionOne);
							CommissionLog commissionLog = new CommissionLog(member.getUserid(), order.getId(), orderProduct.getId(), CommissionLogType.GroupCommissionOne.getType(),
									commissionOne, member.getCentreId());
							commissionService.saveLog(commissionLog);
							commissionIds = commissionIds + commissionLog.getId() + ",";
						}
					}
				}

				//拼团订单二级推荐人分佣
				Double twoCommission = marketingGroup.getTwoCommission();
				if (twoCommission != null && twoCommission > 0 && member.getUpUserid() != null) {
					Member memberResult = memberMapper.selectByPrimaryKey(member.getUpUserid());
					boolean flag = memberService.commissionFlag(memberResult, order.getPortType());
					if (flag) {
						double ratio = twoCommission / 100;
						BigDecimal commissionTwo = order.getPayprice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
						if (commissionTwo.compareTo(BigDecimal.ZERO) > 0) {
							commissionTotal = commissionTotal.add(commissionTwo);
							logger.info("拼团订单二级推荐人分佣----" + commissionTwo);
							CommissionLog commissionLog = new CommissionLog(member.getUpUserid(), order.getId(), orderProduct.getId(), CommissionLogType.GroupCommissionTwo.getType(),
									commissionTwo, member.getCentreId());
							commissionService.saveLog(commissionLog);
							commissionIds = commissionIds + commissionLog.getId() + ",";
						}
					}
				}

				//拼团发起人分佣
				Double sponsorCommission = marketingGroup.getInitiatorCommission();
				if (sponsorCommission != null && sponsorCommission > 0 && order.getSgorderId() != null) {
//					if (sponsorCommission != null && sponsorCommission > 0 && order.getSgorderId() != null && !order.getSgorderId().equals(order.getId())) {
					Order orderResult = orderMapper.selectByPrimaryKey(order.getSgorderId());
					if (orderResult != null) {
						Member memberResult = memberMapper.selectByPrimaryKey(orderResult.getMid());
						boolean flag = memberService.commissionFlag(memberResult, order.getPortType());
						if (!flag) {
							sponsorCommission = marketingGroup.getGeneralMemberCommission();
						}
						double ratio = sponsorCommission / 100;
						BigDecimal commissionSponsor = order.getPayprice().multiply(BigDecimal.valueOf(ratio)).setScale(2, BigDecimal.ROUND_DOWN);
						if (commissionSponsor.compareTo(BigDecimal.ZERO) > 0) {
							commissionTotal = commissionTotal.add(commissionSponsor);
							logger.info("拼团发起人分佣----" + commissionSponsor);
							CommissionLog commissionLog = new CommissionLog(orderResult.getMid(), order.getId(), orderProduct.getId(), CommissionLogType.GroupCommissionSponsor.getType(),
									commissionSponsor, orderResult.getCentreId());
							commissionService.saveLog(commissionLog);
							commissionIds = commissionIds + commissionLog.getId() + ",";
						}
					}
				}

				//计算易票联交易手续费和琰通收取的服务费
				//查询优惠券所属的门店
				Member collectionMember = memberService.getByKey(marketingGroup.getTeamId());
				//线上费率
				Double deductionRatio = centre.getDeductionRatio();
				BigDecimal deductionMoney = order.getPayprice().multiply(BigDecimal.valueOf(deductionRatio / 100)).setScale(2, RoundingMode.DOWN);
				//计算琰通总收取的费率金额
				rateMoneyTotal = rateMoneyTotal.add(deductionMoney);

				//实付减去总佣金减去琰通扣点等于门店实际所得金额
				BigDecimal teamMoney = order.getPayprice().subtract(commissionTotal).subtract(deductionMoney);

				//构建表信息
				orderSplitInfo = new OrderSplitInfo();
				orderSplitInfo.setOrderId(order.getId());
				orderSplitInfo.setOrderProductId(orderProduct.getId());
				orderSplitInfo.setRefId(marketingGroup.getId());
				orderSplitInfo.setOutTradeNo(order.getOutTradeNo());
				orderSplitInfo.setType(1);
				orderSplitInfo.setSplitType(1);
				orderSplitInfo.setMoney(teamMoney);
				orderSplitInfo.setServiceCharge(deductionMoney);
				orderSplitInfo.setServiceChargeRate(BigDecimal.valueOf(deductionRatio));
				orderSplitInfo.setCommissionTotal(commissionTotal);
				orderSplitInfo.setCommission(ValidateUtil.isEmptyString(commissionIds) ? null : commissionIds.substring(0, commissionIds.length() - 1));

				orderSplitInfo.setCentreId(collectionMember.getCentreId());
				orderSplitInfo.setTeamId(collectionMember.getId());
				orderSplitInfo.setStatus(1);
				orderSplitInfo.setPayMid(order.getMid());

				//不是商户下的直属门店
				{
					orderSplitInfo.setRemark("拼团付款，门店无法分账收款，金额分账到商户账户中，给门店发放虚拟余额");
					if (order.getPaytype() != 1) {
						//门店没有分账商户的这笔现金直接分到商户帐号
						splitInfoList.add(new SplitInfo(centre.getYplCustomerCode(), teamMoney.multiply(new BigDecimal("100")).longValue(), 3));
						OrderSplitInfo orderSplitInfo1 = new OrderSplitInfo();
						BeanUtils.copyProperties(orderSplitInfo, orderSplitInfo1);
						orderSplitInfo1.setTeamId(null);
						orderSplitInfo1.setSplitType(2);
						orderSplitInfo1.setYfzServiceChargeFlag(1);
						orderSplitInfo1.setStatus(1);
						orderSplitInfo1.setStatusTime(new Date());
						orderSplitInfo1.setRemark("拼团付款，门店无法分账收款，金额分账到商户账户中");
						orderSplitInfoList.add(orderSplitInfo1);
					} else {
						orderSplitInfo.setRemark("拼团付款，给门店发放虚拟余额");
					}

					orderSplitInfo.setStatusTime(new Date());
					if (collectionMember.getIsHeadOffice() != 1) {
						//加入用户结算余额
						Member member1 = new Member();
						member1.setId(collectionMember.getId());
						member1.setCredit2(collectionMember.getCredit2().add(teamMoney));
						memberService.updateMemberAsync(member1);

						//余额变更记录
						BalanceLog supplyBalanceLog = new BalanceLog();
						supplyBalanceLog.setMid(collectionMember.getId());
						supplyBalanceLog.setMobile(collectionMember.getMobile());
						supplyBalanceLog.setRealname(collectionMember.getRealname());
						supplyBalanceLog.setStatus(0);
						supplyBalanceLog.setType(0);
						supplyBalanceLog.setStyle(BalanceLogStyle.TEAM_SETTLEMENT.getCode());
						supplyBalanceLog.setCredittype("credit2");
						supplyBalanceLog.setBeforeamount(collectionMember.getCredit2());
						supplyBalanceLog.setMoney(orderSplitInfo.getMoney());
						supplyBalanceLog.setAfteramount(collectionMember.getCredit2().add(orderSplitInfo.getMoney()));
						supplyBalanceLog.setCreateTime(new Date());
						supplyBalanceLog.setCentreId(collectionMember.getCentreId());
						supplyBalanceLog.setTitle("拼团成功后结算余额");
						supplyBalanceLog.setRemark("用户使用余额购买拼团产品，拼团成功后结算余额");
						supplyBalanceLog.setSource(0);
						supplyBalanceLog.setFlowtype(BalanceLogFlowType.TEAM_SETTLEMENT.getCode());
						balanceLogService.save(supplyBalanceLog);
					}
				}
				orderSplitInfoList.add(orderSplitInfo);

				if (splitInfo != null) {
					splitInfoList.add(splitInfo);
				}

				if (BigDecimal.ZERO.compareTo(rateMoneyTotal) < 0) {
					OrderSplitInfo orderSplitInfo1 = new OrderSplitInfo();
					orderSplitInfo1.setOrderId(order.getId());
					orderSplitInfo1.setOutTradeNo(order.getOutTradeNo());
					orderSplitInfo1.setType(1);
					orderSplitInfo1.setPayMid(order.getMid());
					if (order.getPaytype() != 1) {
						orderSplitInfo1.setSplitType(2);
						splitInfoList.add(new SplitInfo(ytCentre.getYplCustomerCode(), rateMoneyTotal.multiply(new BigDecimal("100")).longValue(), 0));
					} else {
						orderSplitInfo1.setSplitType(1);
					}
					orderSplitInfo1.setMoney(rateMoneyTotal);
					orderSplitInfo1.setCustomerCode(ytCentre.getYplCustomerCode());
					orderSplitInfo1.setCentreId(ytCentre.getCentreId());
					orderSplitInfo1.setStatus(1);
					orderSplitInfo1.setStatusTime(new Date());
					orderSplitInfo1.setCommissionTotal(BigDecimal.ZERO);
					orderSplitInfo1.setServiceCharge(BigDecimal.ZERO);
					orderSplitInfo1.setServiceChargeRate(BigDecimal.ZERO);
					orderSplitInfo1.setRemark("拼团付款，琰通收取的服务费");
					orderSplitInfoList.add(orderSplitInfo1);
				}

				if (BigDecimal.ZERO.compareTo(commissionTotal) < 0) {
					OrderSplitInfo orderSplitInfo1 = new OrderSplitInfo();
					orderSplitInfo1.setOrderId(order.getId());
					orderSplitInfo1.setOutTradeNo(order.getOutTradeNo());
					orderSplitInfo1.setPayMid(order.getMid());
					orderSplitInfo1.setType(1);
					if (order.getPaytype() != 1) {
						orderSplitInfo1.setSplitType(2);
						splitInfoList.add(new SplitInfo(centre.getYplCustomerCode(), commissionTotal.multiply(new BigDecimal("100")).longValue(), 0));
					} else {
						orderSplitInfo1.setSplitType(1);
					}
					orderSplitInfo1.setMoney(commissionTotal);
					orderSplitInfo1.setCustomerCode(centre.getYplCustomerCode());
					orderSplitInfo1.setCentreId(centre.getCentreId());
					orderSplitInfo1.setStatus(1);
					orderSplitInfo1.setStatusTime(new Date());
					orderSplitInfo1.setCommissionTotal(BigDecimal.ZERO);
					orderSplitInfo1.setServiceCharge(BigDecimal.ZERO);
					orderSplitInfo1.setServiceChargeRate(BigDecimal.ZERO);
					orderSplitInfo1.setRemark("拼团付款，商户收取的费用（佣金，门店无法收取的分账金额等）");
					orderSplitInfoList.add(orderSplitInfo1);
				}

				//将分账信息存入库表
				if (ValidateUtil.isNotEmptyCollection(orderSplitInfoList)) {
					logger.error("orderSplitInfo表存储信息：" + JSONObject.toJSONString(orderSplitInfoList));
					if (ValidateUtil.isNotEmptyCollection(splitInfoList)) {
						//合并重复项  否则易票联分账会报错（重复分账）
						splitInfoList = this.mergeSplitInfoList(splitInfoList);
						for (OrderSplitInfo orderSplitInfo2 : orderSplitInfoList) {
							orderSplitInfo2.setSplitResultInfoList(JSONObject.toJSONString(splitInfoList));
						}
					}
					orderSplitInfoMapper.insertList(orderSplitInfoList);
				}

				logger.error("大礼包分账详细信息：" + JSONObject.toJSONString(splitInfoList));
				//拼团没有退款流程   所以直接先走易票联的延迟分账
				if (ValidateUtil.isNotEmptyCollection(splitInfoList)) {
					request.setOutTradeNo(order.getOutTradeNo());
					request.setCustomerCode(centre.getYplCustomerCode());
					request.setSplitInfoList(splitInfoList);
					request.setNotifyUrl(templatemsgCreateUserUrl + "/notify/yfz/split/call-back");
					try {
						SplitResponse splitResponse = YFZPayutil.split(centre, request);
						orderSplitInfoMapper.updateByOutTradeNoReturn(order.getOutTradeNo(), splitResponse.getReturnCode(), splitResponse.getReturnMsg());
						logger.error("大礼包分账返回信息：" + JSONObject.toJSONString(splitResponse));
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}

			}
		}
		logger.info("佣金发放结束");
	}

	/**
	 * 重置用户所属的推客或管家或主管
	 *
	 * @param relationId 所属关系的用户id
	 * @param userId     推荐人id
	 * @param memberList 所有用户集合
	 * @param role       需设置的所属角色
	 */
	@Override
	public void superiorRole(Long relationId, Long userId, List<Member> memberList, String role) {
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int balanceRefund(WorkOrder workOrder, Long aid, String aname) {
		Long orderId = workOrder.getOid();
		if (orderId == null) {
			return 0;
		}
		Order order = orderMapper.selectByPrimaryKey(orderId);
		if (StringUtils.isEmpty(order.getOutTradeNo())) {
			order.setOutTradeNo("X_OC_".concat(order.getOrdersn()));
		}
		String refundNo = order.getOutTradeNo().concat("WR").concat(workOrder.getId().toString());
		OrderProduct op = orderProductMapper.selectByPrimaryKey(workOrder.getOgid());
		{
			//退款数量
			Integer newRefundNum = op.getRefundNum();
			if (newRefundNum == null) {
				newRefundNum = 0;
			}
			//退款金额
			BigDecimal newRefundPrice = op.getRefundPrice();
			if (newRefundPrice == null) {
				newRefundPrice = BigDecimal.ZERO;
			}
			newRefundNum += workOrder.getNums();
			newRefundPrice = newRefundPrice.add(workOrder.getMoney());
			//把订单修改为已完成
			OrderProduct opP = new OrderProduct();
			if (newRefundNum.intValue() >= op.getTotal().intValue()) {
				opP.setStatus(OrderStatus.cancel.getCode());
			} else {
				opP.setStatus(OrderStatus.delivery_success.getCode());
			}
			opP.setId(workOrder.getOgid());
			opP.setRefundNum(newRefundNum);
			opP.setRefundPrice(newRefundPrice);
			orderProductMapper.updateByPrimaryKeySelective(opP);

			//把订单修改为已完成
			Order orderP = new Order();
			//查询订单状态是否有  != -1的 没有不等于就改为  已退款
			int total = orderProductMapper.countByOrderIdAndNotStatus(workOrder.getOid(), OrderStatus.cancel.getCode());
			if (total == 0) {
				orderP.setStatus(OrderStatus.cancel.getCode());
			} else {
				//查询订单 没有  正在售后的订单  改为  已完成
				int work_accessTotal = orderProductMapper.countByOrderIdAndStatus(workOrder.getOid(), OrderStatus.work_access.getCode());
				if (work_accessTotal <= 0) {
					orderP.setStatus(OrderStatus.delivery_success.getCode());
				}
			}
			newRefundNum += workOrder.getNums();
			newRefundPrice = newRefundPrice.add(workOrder.getMoney());
			orderP.setId(workOrder.getOid());
//			orderP.setRefundNum(newRefundNum);
//			orderP.setRefundPrice(newRefundPrice);
			orderMapper.updateByPrimaryKeySelective(orderP);
		}


		if (op.getIsKuaidi() == 0) {
			//商户扣除余额,门店加余额
			balanceService.takeMoney(order.gettMid(), workOrder.getMoney().doubleValue(),
					BalanceLogStyle.ORDER_REFUND.getCode(), RechargeType.ORDER_REFUND.getType(), order.getOrdersn(), workOrder.getWorksn(), order.getCentreId());
		} else {
			//商户扣除余额,用户加余额
			balanceService.takeMoney(order.getMid(), workOrder.getMoney().doubleValue(),
					BalanceLogStyle.ORDER_REFUND.getCode(), RechargeType.ORDER_REFUND.getType(), order.getOrdersn(), workOrder.getWorksn(), order.getCentreId());
		}



		payService.yfzRefundDispose(order.getOutTradeNo(), null, order);

		return 1;
	}

	@Override
	public String enterpriceToCustomer(String opendId, Double amount, String realname, String applyNo, String desc) {
		SortedMap<Object, Object> params = new TreeMap<>();
		//微信公众号的appid
		params.put("mch_appid", wxAppId);
		//商务号
		params.put("mchid", wxMchId);
		//随机生成后数字，保证安全性
		params.put("nonce_str", CommonUtils.getRandomString(32));
		//生成商户订单号
		params.put("partner_trade_no", applyNo);
		// 支付给用户openid
		params.put("openid", opendId);
		//是否验证真实姓名呢
		params.put("check_name", "NO_CHECK");
		//收款用户姓名
		params.put("re_user_name", realname);
		//企业付款金额，单位为分
		params.put("amount", amount.intValue());
		//企业付款操作说明信息。必填。
		params.put("desc", desc);
		//调用接口的机器Ip地址
		params.put("spbill_create_ip", wxIp);
		String sign = SignUtils.creatSign("utf-8", params, paySignKey);
		//4   封装退款对象
		params.put("sign", sign);

		//5  将当前的map结合转化成xml格式
		String requestXml = WXPayUtil.getRequestXml(params);
		logger.info("微信支付，请求xml:{}", requestXml);
		try {
			String weixinPost = ClientCustomSSL.doRefund(wxEnterpriceUrl, requestXml, wxcertificatePath, wxMchId);
			EnterpriceToCustomerEntity etoc = EnterpricePayXmlToBeanUtils.parseXmlToMapEnterpriceToCustomer(weixinPost);
			if ("SUCCESS".equalsIgnoreCase(etoc.getResult_code()) && "SUCCESS".equalsIgnoreCase(etoc.getReturn_code())) {
				return etoc.getPayment_no();
			} else {
				//微信小程序的appid
				params.put("mch_appid", wxMiniAppsAppId);
				sign = SignUtils.creatSign("utf-8", params, paySignKey);
				//4   封装退款对象
				params.put("sign", sign);
				//5  将当前的map结合转化成xml格式
				requestXml = WXPayUtil.getRequestXml(params);
				logger.info("进入微信小程序appid提现", requestXml);
				weixinPost = ClientCustomSSL.doRefund(wxEnterpriceUrl, requestXml, wxcertificatePath, wxMchId);
				etoc = EnterpricePayXmlToBeanUtils.parseXmlToMapEnterpriceToCustomer(weixinPost);
				if ("SUCCESS".equalsIgnoreCase(etoc.getResult_code()) && "SUCCESS".equalsIgnoreCase(etoc.getReturn_code())) {
					return etoc.getPayment_no();
				}
			}

			logger.info("微信支付，返回etoc:{}", etoc);
			return null;
		} catch (Exception e) {
			logger.error("weixin pay error:{}", e.getMessage());
		}
		return null;
	}
//
	/**
	 * 企业支付到个人零钱 站点开的小程序
	 *
	 * @param opendId
	 * @param amount
	 * @param realname
	 * @param applyNo
	 * @param desc
	 * @return
	 */
	@Override
	public String enterpriceToCustomerByCentre(String opendId, Double amount, String realname, String applyNo,
	                                           String desc, Centre centre, String appOpenid) {
		if (StringUtils.isEmpty(centre.getRelateAccount())) {
			return null;
		}
		if (StringUtils.isNotEmpty(appOpenid)) {
			opendId = appOpenid;
		}
		SortedMap<Object, Object> params = new TreeMap<>();
		//微信公众号的appid
		params.put("mch_appid", ConfigUtil.returnConfiguration(centre.getRelateAccount(), 0));
		//商务号
		params.put("mchid", ConfigUtil.returnConfiguration(centre.getRelateBusi(), 0));
		//随机生成后数字，保证安全性
		params.put("nonce_str", CommonUtils.getRandomString(32));
		//生成商户订单号
		params.put("partner_trade_no", applyNo);
		// 支付给用户openid
		params.put("openid", opendId);
		//是否验证真实姓名呢
		params.put("check_name", "NO_CHECK");
		//收款用户姓名
		params.put("re_user_name", realname);
		//企业付款金额，单位为分
		params.put("amount", amount.intValue());
		//企业付款操作说明信息。必填。
		params.put("desc", desc);
		//调用接口的机器Ip地址
		params.put("spbill_create_ip", ConfigUtil.returnConfiguration(centre.getController(), 0));
		String sign = SignUtils.creatSign("utf-8", params, ConfigUtil.returnConfiguration(centre.getBusiEmail(), 0));
		//4   封装退款对象
		params.put("sign", sign);

		//5  将当前的map结合转化成xml格式
		String requestXml = WXPayUtil.getRequestXml(params);
		logger.info("微信支付，请求xml:{}", requestXml);
		try {
			String weixinPost = ClientCustomSSL.doRefund(wxEnterpriceUrl, requestXml, centre.getBusiMobile(), centre.getRelateBusi());
			EnterpriceToCustomerEntity etoc = EnterpricePayXmlToBeanUtils.parseXmlToMapEnterpriceToCustomer(weixinPost);
			if ("SUCCESS".equalsIgnoreCase(etoc.getResult_code()) && "SUCCESS".equalsIgnoreCase(etoc.getReturn_code())) {
				return etoc.getPayment_no();
			}
			logger.info("微信支付，返回etoc:{}", etoc);
			return null;
		} catch (Exception e) {
			logger.error("weixin pay error:{}", e.getMessage());
		}
		return null;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int juhePay(Long orderId, String payId, String outTradeNo, Long procedureFee) {
		int updateResult = 0;
		JuheOrder juheOrder = juheOrderMapper.selectOrderByOutTradeNo(outTradeNo);
		logger.info("聚合支付订单信息-----------------" + JSONObject.toJSONString(juheOrder));

		if (null != juheOrder) {

			//查询商户信息
			Centre centre = centreService.getCentreById(juheOrder.getCenterId());
			Centre ytCentre = centreService.getCentreById(317L);

			Member member = memberService.getByKey(juheOrder.getMid());
			logger.info("聚合支付类型优惠券赠送人信息-----------------" + JSONObject.toJSONString(member));
			updateResult = juheOrderMapper.updaPayParams(payId, PayStatus.PAY_SUCCESS.getCode(), BigDecimal.valueOf(procedureFee).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN), juheOrder.getId());

			//添加支付流水
			Payment payment = new Payment();
			payment.setPayTradeNo(juheOrder.getRefundNo());
			payment.setOutTradeNo(juheOrder.getOutTradeNo());
			payment.setMoney(juheOrder.getOrderprice());
			payment.setStatus(2);
			payment.setType(juheOrder.getPayType().toString());
			payment.setStyle(4);
			payment.setTuikuanstatus(1);
			payment.setUpdateTime(new Date());
			paymentService.savePayment(payment);

			//核销优惠券
			if (juheOrder.getTrId() != null) {
				TicketRecord record = ticketRecordMapper.getByKey(juheOrder.getTrId());
				int count = record.getCountUsed() + 1;
				if (record.getCount() <= count) {
					record.setStatus(TicketStatus.USED.getStatus());
				}
				record.setCountUsed(count);
				ticketRecordMapper.updateByPrimaryKeySelective(record);
			}

			if (member != null) {
				//赠送优惠券（赠送门店下面的聚合支付赠送类型的优惠券）
				List<Ticket> ticketVo;
				Map<String, Object> queryMap = new HashMap<>();
				//queryMap.put("type", TicketType.JUHEPAY.getCode());
				//是否聚合支付赠送 0-否，1-是
				queryMap.put("isJuhepayTicket", 1);
				queryMap.put("teamId", juheOrder.getTeamId());
				ticketVo = ticketMapper.queryList(queryMap);
				String content = "";
				if (ValidateUtil.isNotEmptyCollection(ticketVo)) {
					content = "支付成功，赠送优惠券如下：" + "\n";
				} else {
					content = "支付成功";
				}
				logger.info("聚合支付类型优惠券-----------------" + JSONObject.toJSONString(ticketVo));
				if (ValidateUtil.isNotEmptyCollection(ticketVo) && member != null) {
					for (Ticket ticket : ticketVo) {
						if (!member.getCentreId().equals(ticket.getCentreId())) {
							logger.info("用户归属商户与优惠券不一致");
							continue;
						}
						//生成未领取记录
						TicketRecord ticketRecord = new TicketRecord();
						ticketRecord.setTicketId(ticket.getId());
						ticketRecord.setMid(member.getId());
						ticketRecord.setStartTime(ticket.getStartTime());
						ticketRecord.setGetTime(new Date());
						ticketRecord.setEndTime(ticket.getEndTime());
						if (ticket.getEndTime() == null && ticket.getPeriod() != null) {
							ticketRecord.setEndTime(DateUtils.getAddDayDate(new Date(), ticket.getPeriod()));
						}
						ticketRecord.setStatus(0);
						ticketRecord.setNum(ticket.getCount());
						ticketRecord.setCount(ticket.getCount());
						ticketRecord.setCentreId(ticket.getCentreId());
						ticketRecord.setTicketType(0);
						ticketRecord.setTeamId(ticket.getTeamId());
						ticketRecord.setOrderId(juheOrder.getId());
						ticketRecord.setRemark("扫码支付赠送");
						logger.info("聚合支付类型优惠券实际赠送-----------------" + JSONObject.toJSONString(ticketRecord));

						if (ticketRecordMapper.insertSelective(ticketRecord) > 0) {
							content += ticket.getTicketName() + "\n";
						}
						content = content + "\n" + "欢迎光临琰通本地生活使用此券！" + templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/user/card-package";


					}

					//发送文本通知
					if (ValidateUtil.isNotEmptyString(member.getOpenid())) {

						logger.info("聚合支付赠送优惠券公众号文本消息发送------------------");
						WxNotifyParam notifyParam = new WxNotifyParam();
						notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEXT.getType());//文本消息
						notifyParam.setCenterId(member.getCentreId());
						notifyParam.setGzhOpenId(member.getOpenid());
						notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
						notifyParam.setContent(content);
						notifyParam.setUrl(templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/user/card-package");
						wxNotifyService.sendNotify(notifyParam);

//					logger.info("聚合支付赠送优惠券小程序文本消息发送------------------");
//					WxNotifyParam notifyParam1 = new WxNotifyParam();
//					notifyParam1.setMessageType(WxMessageType.MESSAGE_TYPE_TEXT.getType());//文本消息
//					notifyParam1.setCenterId(member.getCentreId());
//					notifyParam1.setGzhOpenId(member.getOpenid());
//					notifyParam1.setTeminal(WxTerminal.TERMINAL_XCX.getTerminal());
//					notifyParam1.setContent(content);
//					notifyParam1.setUrl(templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/user/card-package");
//					wxNotifyService.sendNotify(notifyParam1);

					}


				}

			}
			Member collectionMember = memberService.getByKey(juheOrder.getTeamId());
			//分账处理
			//线下费率
			Double deductionRatio = centre.getOfflineDeductionRatio() / 100;
			BigDecimal deductionMoney = juheOrder.getPayprice().multiply(BigDecimal.valueOf(deductionRatio)).setScale(2, RoundingMode.DOWN);

			//库表分账信息list
			List<OrderSplitInfo> orderSplitInfoList = new ArrayList<>();
			//易票联分账详细信息
			List<SplitInfo> splitInfoList = new ArrayList<>();
			//实付减去总佣金减去琰通扣点等于门店实际所得金额
			BigDecimal teamMoney = juheOrder.getPayprice().subtract(deductionMoney);

			//构建表信息
			OrderSplitInfo orderSplitInfo = new OrderSplitInfo();
			orderSplitInfo.setOrderId(juheOrder.getId());
			orderSplitInfo.setOutTradeNo(juheOrder.getOutTradeNo());
			orderSplitInfo.setType(2);
			orderSplitInfo.setSplitType(2);
			orderSplitInfo.setMoney(teamMoney);
			orderSplitInfo.setServiceCharge(deductionMoney);
			orderSplitInfo.setServiceChargeRate(BigDecimal.valueOf(deductionRatio));
			orderSplitInfo.setCentreId(collectionMember.getCentreId());
			orderSplitInfo.setTeamId(collectionMember.getId());
			orderSplitInfo.setCommissionTotal(BigDecimal.ZERO);
			orderSplitInfo.setStatus(0);
			orderSplitInfo.setPayMid(juheOrder.getMid());
			SplitInfo splitInfo = null;
			 {
				splitInfo = new SplitInfo(centre.getYplCustomerCode(), teamMoney.multiply(new BigDecimal("100")).longValue(), 3);
				OrderSplitInfo centreOrderSplitInfo = new OrderSplitInfo();
				BeanUtils.copyProperties(orderSplitInfo, centreOrderSplitInfo);
				centreOrderSplitInfo.setTeamId(null);
				centreOrderSplitInfo.setYfzServiceChargeFlag(1);
				centreOrderSplitInfo.setStatus(1);
				centreOrderSplitInfo.setPayMid(juheOrder.getMid());
				centreOrderSplitInfo.setStatusTime(new Date());
				centreOrderSplitInfo.setRemark("聚合支付，门店无法分账收款，金额分账到商户账户中");
				orderSplitInfoList.add(centreOrderSplitInfo);

				orderSplitInfo.setSplitType(1);
				orderSplitInfo.setStatus(1);
				orderSplitInfo.setStatusTime(new Date());
				orderSplitInfo.setRemark("聚合支付，门店无法分账收款，金额分账到商户账户中，给门店发放虚拟余额");
				if (collectionMember.getIsHeadOffice() != 1) {
					//余额变更记录
					BalanceLog supplyBalanceLog = new BalanceLog();
					supplyBalanceLog.setMid(collectionMember.getId());
					supplyBalanceLog.setMobile(collectionMember.getMobile());
					supplyBalanceLog.setRealname(collectionMember.getRealname());
					supplyBalanceLog.setStatus(0);
					supplyBalanceLog.setType(0);
					supplyBalanceLog.setStyle(BalanceLogStyle.JUHE_SETTLEMENT.getCode());
					supplyBalanceLog.setCredittype("credit2");
					supplyBalanceLog.setBeforeamount(collectionMember.getCredit2());
					supplyBalanceLog.setMoney(orderSplitInfo.getMoney());
					supplyBalanceLog.setAfteramount(collectionMember.getCredit2().add(orderSplitInfo.getMoney()));
					supplyBalanceLog.setCreateTime(new Date());
					supplyBalanceLog.setCentreId(collectionMember.getCentreId());
					supplyBalanceLog.setTitle("聚合支付结算余额");
					supplyBalanceLog.setRemark("用户使用聚合支付付款后后结算余额");
					supplyBalanceLog.setSource(0);
					supplyBalanceLog.setFlowtype(BalanceLogFlowType.JUHE_SETTLEMENT.getCode());
					balanceLogService.save(supplyBalanceLog);

					//加入用户结算金额
					Member member1 = new Member();
					member1.setId(collectionMember.getId());
					member1.setCredit2(collectionMember.getCredit2().add(teamMoney));
					memberService.updateMemberAsync(member1);
				}
			}
			orderSplitInfoList.add(orderSplitInfo);

			if (splitInfo != null) {
				splitInfoList.add(splitInfo);
			}

			if (BigDecimal.ZERO.compareTo(deductionMoney) < 0) {
				splitInfoList.add(new SplitInfo(ytCentre.getYplCustomerCode(), deductionMoney.multiply(new BigDecimal("100")).longValue(), 0));
				OrderSplitInfo orderSplitInfo1 = new OrderSplitInfo();
				orderSplitInfo1.setOrderId(juheOrder.getId());
				orderSplitInfo1.setOutTradeNo(juheOrder.getOutTradeNo());
				orderSplitInfo1.setType(2);
				orderSplitInfo1.setSplitType(2);
				orderSplitInfo1.setMoney(deductionMoney);
				orderSplitInfo1.setCustomerCode(ytCentre.getYplCustomerCode());
				orderSplitInfo1.setCentreId(ytCentre.getCentreId());
				orderSplitInfo1.setStatus(1);
				orderSplitInfo1.setStatusTime(new Date());
				orderSplitInfo1.setPayMid(juheOrder.getMid());
				orderSplitInfo1.setCommissionTotal(BigDecimal.ZERO);
				orderSplitInfo1.setServiceCharge(BigDecimal.ZERO);
				orderSplitInfo1.setServiceChargeRate(BigDecimal.ZERO);
				orderSplitInfo1.setSplitResultInfoList("聚合支付，琰通收取的服务费");
				orderSplitInfoList.add(orderSplitInfo1);
			}

			//将分账信息存入库表
			if (ValidateUtil.isNotEmptyCollection(orderSplitInfoList)) {
				logger.error("orderSplitInfo表存储信息：" + JSONObject.toJSONString(orderSplitInfoList));
				if (ValidateUtil.isNotEmptyCollection(splitInfoList)) {
					//合并重复项  否则易票联分账会报错（重复分账）
					splitInfoList = this.mergeSplitInfoList(splitInfoList);
					for (OrderSplitInfo orderSplitInfo2 : orderSplitInfoList) {
						orderSplitInfo2.setSplitResultInfoList(JSONObject.toJSONString(splitInfoList));
					}
				}
				orderSplitInfoMapper.insertList(orderSplitInfoList);
			}

			logger.error("聚合支付分账详细信息：" + JSONObject.toJSONString(splitInfoList));

			//分账参数信息
			SplitRequest request = new SplitRequest();
			//聚合支付没有退款流程   所以直接先走易票联的延迟分账
			request.setOutTradeNo(juheOrder.getOutTradeNo());
			request.setCustomerCode(centre.getYplCustomerCode());
			request.setSplitInfoList(splitInfoList);
			request.setNotifyUrl(templatemsgCreateUserUrl + "/notify/yfz/split/call-back");
			try {
				SplitResponse splitResponse = YFZPayutil.split(centre, request);
				orderSplitInfoMapper.updateByOutTradeNoReturn(juheOrder.getOutTradeNo(), splitResponse.getReturnCode(), splitResponse.getReturnMsg());
				logger.error("聚合支付分账返回信息：" + JSONObject.toJSONString(splitResponse));
			} catch (Exception ex) {
				ex.printStackTrace();
			}

			//喇叭提醒
//			orderService.pushHornJuheorder(juheOrder, HornPricettsType.OrderPay.getType());
		}
		return updateResult;
	}

	/**
	 * 合并重复项  否则易票联分账会报错（重复分账）
	 */
	private List<SplitInfo> mergeSplitInfoList(List<SplitInfo> splitInfoList) {
		List<SplitInfo> newSplitInfoList = new ArrayList<>();
		List<String> list = new ArrayList<>();
		for (SplitInfo splitInfo : splitInfoList) {
			if (!list.contains(splitInfo.getCustomerCode())) {
				list.add(splitInfo.getCustomerCode());
				long amount = 0L;
				SplitInfo newSplitInfo = new SplitInfo();
				newSplitInfo.setIsProcedureCustomer(0);
				newSplitInfo.setCustomerCode(splitInfo.getCustomerCode());

				for (SplitInfo splitInfo2 : splitInfoList) {
					if (splitInfo2.getCustomerCode().equals(splitInfo.getCustomerCode())) {
						amount = amount + splitInfo2.getAmount();
						if (splitInfo2.getIsProcedureCustomer() == 3) {
							newSplitInfo.setIsProcedureCustomer(3);
						}
					}
				}
				newSplitInfo.setAmount(amount);
				newSplitInfoList.add(newSplitInfo);
			}
		}
		return newSplitInfoList;
	}
	/**
	 * 计算积分抵扣金额
	 *
	 * @param integral 积分数
	 * @return
	 */
	private BigDecimal calcIntegralDeductPrice(Integer integral, Long centreId) {
		BigDecimal deductPrice = new BigDecimal(0);
		if (integral != null) {
			double exchange = 100d;
			//TradeConfig tradeConfig = configService.getTradeConfig(null);修改之前
			TradeConfig tradeConfig = configService.getTradeConfig(centreId);
			if (tradeConfig != null && tradeConfig.getExchangeIntegral() != null) {
				exchange = tradeConfig.getExchangeIntegral();
			}
			deductPrice = new BigDecimal(integral).divide(BigDecimal.valueOf(exchange), 2, BigDecimal.ROUND_HALF_UP);
		}
		return deductPrice;
	}
	/**
	 * 校验拼团订单
	 *
	 * @return
	 */
	public int verificationSpellGroup(Order order) {
		int num = 0;
		//发起人的拼团人数+1
		Order sgOrder = orderService.getByKey(order.getSgorderId());
		sgOrder.setPeoplenum(sgOrder.getPeoplenum() == null ? 1 : sgOrder.getPeoplenum() + 1);
		logger.info("=verificationSpellGroup==sgOrder.getPeoplenum()===" + sgOrder.getPeoplenum());
		num = orderMapper.updateByPrimaryKeySelective(sgOrder);

		//查询拼团发起人订单
		List<OrderProductDetailVo> list = orderMapper.getSpellGroupByOrderId(order.getSgorderId());
		if (CollectionUtils.isNotEmpty(list)) {
			Long activityId = list.get(0).getActivityId() == null ? 0L : list.get(0).getActivityId();
			//查询到商品
			MarketingGroup marketingGroup = marketingGroupMapper.getMarketingGroupById(activityId);

			//开团
			if (sgOrder.getPeoplenum() == 1) {
				orderService.sendTeamBegin(order, marketingGroup);
			}

			//商品成团人数小于等于订单成团人数
			if (marketingGroup != null && marketingGroup.getNeedJoinGroupNum() <= list.get(0).getPeoplenum()) {
				if (GroupTypeEnum.RANDOM.getCode().equals(marketingGroup.getType())) {
					//查询该拼团的所有订单
					SpellGroupOrdVo vo = new SpellGroupOrdVo();
					vo.setSgorderId(list.get(0).getId());
					vo.setSpellgroupStu(OrderSpellGroupStatus.SPELL_SUCCESS.getCode());
					List<Order> ords = orderMapper.getOrderByStu(vo);
					//改成已拼团成功
					for (Order ord : ords) {
						SpellGroupOrdVo spellGroupOrdVo = new SpellGroupOrdVo();
						spellGroupOrdVo.setOrderid(ord.getId());
						spellGroupOrdVo.setSpellgroupStu(OrderSpellGroupStatus.SPELL_SUCCESS.getCode());
						//修改订单商品拼团状态
						orderProductMapper.updSpellgroupStu(spellGroupOrdVo);
						//修改订单拼团成功
						orderMapper.updateSpellGroupOrdStu(spellGroupOrdVo);

						//大礼包拼团中的大礼包业务处理
						if (MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(marketingGroup.getMarketingGroupType())) {
							this.freeChargeCallback(ord.getId(), ord, null, ord);
							//大礼包拼团不需要发货   直接分佣(拼团相关的分佣)
							this.marketingGroupCommission(ord);
						}
					}
					//修改订单拼团成功
					orderMapper.updateSpellGroupOrdStu(vo);
					//发送订阅消息
//					orderService.sendTeamSucceed(order, marketingGroup, list.get(0));

					List<Order> list2 = orderMapper.getOrderByTeam(vo);
					if (ValidateUtil.isNotEmptyCollection(list2)) {
						for (Order order1 : list2) {

							//发送拼团成功公众号消息
							Map<String, String> map2 = new HashMap<>();
							String url = null;
							List<OrderProduct> listproduct = orderProductMapper.getByOrderId(order1.getId());
							String productName2 = listproduct.get(0).getProductName();//商品名
							String firstString = "拼团成功通知:";
							Member member = memberService.getByKey(order1.getMid());
							url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/index.html";
							map2.put("firstString", firstString);
							map2.put("productName", productName2);
							map2.put("payPrice", String.valueOf(order1.getPayprice()));
							map2.put("teamCount", String.valueOf(marketingGroup.getNeedJoinGroupNum()));
							map2.put("remark", "拼团时间:" + DateUtil.convertDateToStr(order1.getPayTime() == null ? new Date() : order1.getPayTime(), DateUtil.yyyy_MM_dd_HH_mm_ss));
							orderService.sendGZHTeamSucceed(member.getCentreId(), member.getId(), map2, url);
						}
					}
				} else {
					//盲拼
					this.marketingSnapUpDispose(marketingGroup, sgOrder);
				}
			} else {
				//等待成团
				orderService.sendTeamAwait(order, marketingGroup, list.get(0).getPeoplenum());
			}
		}
		return num;
	}

	/**
	 * 拼团抢购的业务处理
	 */
	@Override
	public void marketingSnapUpDispose(MarketingGroup marketingGroup, Order sgOrder) {
		SpellGroupOrdVo vo = new SpellGroupOrdVo();
		vo.setSgorderId(sgOrder.getId());
		//去掉发起人订单
		vo.setSpellgroupFlag(true);
		List<Order> ords = orderMapper.getOrderByStu(vo);
		logger.info("发起人----------------------------------------" + JSONObject.toJSONString(sgOrder));
		logger.info("除发起人外的团购成员=----------------------------------------" + JSONObject.toJSONString(ords));
		//中奖订单
		List<Order> resultOrder = new ArrayList<>();
		//未中订单
		List<Order> resultMissOrder = new ArrayList<>();
		if (MarketingGroupRulesEnum.WINNING.getCode().equals(sgOrder.getGroupRules())) {
			resultOrder = getRandomList(ords, marketingGroup.getWinningNumber() - 1);
			resultOrder.add(sgOrder);
		} else if (MarketingGroupRulesEnum.MISS.getCode().equals(sgOrder.getGroupRules())) {
			//必不中
			resultOrder = getRandomList(ords, marketingGroup.getWinningNumber());
			resultMissOrder.add(sgOrder);
		} else if (MarketingGroupRulesEnum.RANDOM.getCode().equals(sgOrder.getGroupRules())) {
			ords.add(sgOrder);
			resultOrder = getRandomList(ords, marketingGroup.getWinningNumber());
		}

		//获取拼团失败订单
		if (ValidateUtil.isNotEmptyCollection(ords) && ValidateUtil.isNotEmptyCollection(resultOrder)) {
			for (Order order1 : ords) {
				boolean bol = true;
				for (Order order2 : resultOrder) {
					if (order1.getId().equals(order2.getId())) {
						bol = false;
						break;
					}
				}
				if (bol) {
					resultMissOrder.add(order1);
				}
			}
		}

		logger.info("拼团中奖=----------------------------------------" + JSONObject.toJSONString(resultOrder));
		logger.info("拼团未未未中奖=----------------------------------------" + JSONObject.toJSONString(resultMissOrder));

		List<OrderProductDetailVo> list = orderMapper.getSpellGroupByOrderId(sgOrder.getId());

		//拼团成功统一业务处理
		for (Order order1 : resultOrder) {
			SpellGroupOrdVo spellGroupOrdVo = new SpellGroupOrdVo();
			spellGroupOrdVo.setOrderid(order1.getId());
			spellGroupOrdVo.setSpellgroupStu(OrderSpellGroupStatus.SPELL_SUCCESS.getCode());
			//修改订单商品拼团状态
			orderProductMapper.updSpellgroupStu(spellGroupOrdVo);
			//修改订单拼团成功
			spellGroupOrdVo.setPanicBuyingStatus(0);
			orderMapper.updateSpellGroupOrdStu(spellGroupOrdVo);
			Member member = memberService.getByKey(order1.getMid());

			//大礼包拼团中的大礼包业务处理
			if (MarketingGroupTypeEnum.GIFT_BAG.getCode().equals(marketingGroup.getMarketingGroupType())) {
				this.freeChargeCallback(order1.getId(), order1, null, order1);

				//大礼包拼团不需要发货   直接分佣(拼团相关的分佣)
				this.marketingGroupCommission(order1);
			}

			//发送拼团成功公众号消息
			Map<String, String> map2 = new HashMap<>();
			String url = null;
			List<OrderProduct> listproduct = orderProductMapper.getByOrderId(order1.getId());
			String productName2 = listproduct.get(0).getProductName();//商品名
			String firstString = "拼团成功通知:";
			url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/index.html";
			map2.put("firstString", firstString);
			map2.put("productName", productName2);
			map2.put("payPrice", String.valueOf(order1.getPayprice()));
			map2.put("teamCount", String.valueOf(marketingGroup.getNeedJoinGroupNum()));
			map2.put("remark", "拼团时间:" + DateUtil.convertDateToStr(order1.getPayTime() == null ? new Date() : order1.getPayTime(), DateUtil.yyyy_MM_dd_HH_mm_ss));
			orderService.sendGZHTeamSucceed(member.getCentreId(), member.getId(), map2, url);
		}

		//拼团失败统一业务处理
		for (Order order1 : resultMissOrder) {
			Order orderParam = new Order();
			SpellGroupOrdVo spellGroupOrdVo = new SpellGroupOrdVo();

			if (!MarketingGroupRulesEnum.MISS.getCode().equals(order1.getGroupRules())) {
				//退款
				orderService.cancelOrder(order1.getId(), 1);
			} else {
				orderParam.setStatus(OrderStatus.cancel.getCode());
				spellGroupOrdVo.setStatus(OrderStatus.cancel.getCode());
			}


			orderParam.setId(order1.getId());
			orderParam.setPanicBuyingStatus(1);
			orderParam.setSpellgroupStu(OrderSpellGroupStatus.SPELL_FAILED.getCode());
			orderMapper.updateByPrimaryKeySelective(orderParam);


			spellGroupOrdVo.setOrderid(order1.getId());
			spellGroupOrdVo.setSpellgroupStu(OrderSpellGroupStatus.SPELL_FAILED.getCode());
			//修改订单商品拼团状态
			orderProductMapper.updSpellgroupStu(spellGroupOrdVo);

			//购买人信息查询
			Member member = memberService.getByKey(order1.getMid());
			logger.info("购买人信息-------------------member" + JSONObject.toJSONString(member));
			logger.info("开始拼团失败赠送逻辑-------------------marketingGroup" + JSONObject.toJSONString(marketingGroup));
			if (member != null) {
				//赠送内容
				StringBuffer str = new StringBuffer(StringConstans.STR_EMPTY);
				StringBuffer str1 = new StringBuffer(StringConstans.STR_EMPTY);
				StringBuffer str2 = new StringBuffer(StringConstans.STR_EMPTY);
				StringBuffer str3 = new StringBuffer(StringConstans.STR_EMPTY);
				if (marketingGroup.getIsCoupons() == 1 && ValidateUtil.isNotEmptyString(marketingGroup.getTicketIds())) {
					str1.append("优惠劵补贴：");
					List<TicketDTO> ticketsList = JSONObject.parseArray(marketingGroup.getTicketIds(), TicketDTO.class);

					logger.info("需赠送的优惠券-------------------ticketsList" + JSONObject.toJSONString(ticketsList));

					//赠送优惠券
					for (TicketDTO ticketDTO : ticketsList) {
						Ticket yhticket = ticketMapper.selectByPrimaryKey(ticketDTO.getId());
						if (yhticket != null) {
							TicketRecord record = new TicketRecord();
							record.setMid(member.getId());
							record.setTicketId(yhticket.getId());
							record.setNum(yhticket.getCount());
							record.setCentreId(yhticket.getCentreId());
							record.setTicketType(TicketRecordType.NORMAL.getType());
							record.setOrderId(order1.getId());
							ticketService.sendTicket(record);
							str1.append(yhticket.getTicketName()).append(StringConstans.STR_SIGN_COMMA);
						}
					}
					str1.append("\n");
				}
				if (marketingGroup.getIsBalance() == 1 && marketingGroup.getMoney() != null && marketingGroup.getMoney().compareTo(BigDecimal.ZERO) > 0) {
					//赠送余额
					member.setCredit2(member.getCredit2().add(marketingGroup.getMoney()));
					memberService.updateMemberAsync(member);
					//余额记录新增
					BalanceLog supplyBalanceLog = new BalanceLog();
					supplyBalanceLog.setMid(member.getId());
					supplyBalanceLog.setMobile(member.getMobile());
					supplyBalanceLog.setRealname(member.getRealname());
					supplyBalanceLog.setStatus(0);
					supplyBalanceLog.setType(0);
					supplyBalanceLog.setStyle(BalanceLogStyle.MARKETING_GROUP.getCode());
					supplyBalanceLog.setCredittype("credit2");
					supplyBalanceLog.setBeforeamount(member.getCredit2());
					supplyBalanceLog.setMoney(marketingGroup.getMoney());
					supplyBalanceLog.setAfteramount(member.getCredit2().add(marketingGroup.getMoney()));
					supplyBalanceLog.setCreateTime(new Date());
					supplyBalanceLog.setCentreId(member.getCentreId());
					supplyBalanceLog.setTitle("拼团商品抢购");
					supplyBalanceLog.setRemark("抢购失败奖励");
					supplyBalanceLog.setSource(0);
					supplyBalanceLog.setFlowtype(BalanceLogFlowType.MARKETING_GROUP.getCode());
					supplyBalanceLog.setOrderId(order1.getId());
					balanceLogService.save(supplyBalanceLog);
					str2.append("红包补贴：");
					str2.append(marketingGroup.getMoney()).append("\n");
				}
				if (marketingGroup.getIsIntegral() == 1 && marketingGroup.getIntegral() != null && marketingGroup.getIntegral() > 0) {
					str3.append("金币补贴：");
					memberIntegralServicep.addMemberIntegral(member.getId(), BigDecimal.valueOf(marketingGroup.getIntegral()), order1.getId(), "拼团失败赠送金币");
					str3.append(marketingGroup.getIntegral()).append("个").append("\n");
				}
				str = str.append(str1).append(str2).append(str3);

				if (ValidateUtil.isNotEmptyString(member.getOpenid())) {
					List<OrderProduct> orderProductList = orderProductMapper.getByOrderId(order1.getId());
					Map<String, String> map = new HashMap<>();
					String url = null;
					String productName = null;
					String firstString = "拼团通知:";
					url = templatemsgCreateUserUrl + "/bdsh/"+member.getCentreId()+"/index.html";
					if (ValidateUtil.isNotEmptyCollection(orderProductList)) {
						int productNum = orderProductList.size();
						productName = StringConstans.STR_EMPTY;
						if (productNum == 1) {
							productName = orderProductList.get(0).getProductName();
						}
						if (productNum > 1) {
							productName = orderProductList.get(0).getProductName() + "等" + productNum + "件";
						}
					}
					map.put("firstString", firstString);
					map.put("productName", productName);
					map.put("payprice", order1.getPayprice() + StringConstans.STR_EMPTY);
					map.put("failreason", "很遗憾抢购没有成功");
					map.put("remark", str.toString());
					orderService.sendGZHTeamFailed(member.getCentreId(), member.getId(), map, url);
				}
			}
		}
	}

	/**
	 * 退款业务逻辑处理
	 */
	@Override
	public void yfzRefundDispose(String outTradeNo, JuheOrder juheOrder, Order order) {
		//将所有的分账记录失效
		List<OrderSplitInfo> list = orderSplitInfoMapper.selectByOutTradeNo(outTradeNo);
		list.forEach(item -> {
			//先将状态修改为过期和已售后
			item.setStatus(3);
			item.setVerifyFlag(2);
			orderSplitInfoMapper.updateByPrimaryKeySelective(item);
			if (item.getTeamId() != null) {
				Member member = memberService.getByKey(item.getTeamId());
				if (item.getSplitType() == 1) {
					//余额结算，扣除冻结余额
					member.setNoSettlementCredit2(member.getNoSettlementCredit2().subtract(item.getMoney()));
					memberService.updateMember(member);
				} else {
					//易票联分账结算，扣除冻结余额
					member.setNoSettlementMoney(member.getNoSettlementMoney().subtract(item.getMoney()));
					memberService.updateMember(member);
				}
			}
		});
		//将赠送的券修改为无效的关键参数
		Long ticketOrderId = null;
		if (juheOrder != null) {
			ticketOrderId = juheOrder.getId();
			//修改订单状态
			juheOrder.setPaystatus(4);
			juheOrderMapper.updateById(juheOrder);
		} else if (order != null) {
			ticketOrderId = order.getId();
			//将佣金修改为失效
			commissionLogMapper.updateCommissionByOrderId(order.getId());
			//修改订单状态
			order.setPaystatus(PayStatus.REFUND_SUCCESS.getCode());
			order.setStatus(OrderStatus.cancel.getCode());
			orderService.update(order);
			OrderProductExample ope = new OrderProductExample();
			ope.or().andOrderidEqualTo(order.getId());
			OrderProduct record = new OrderProduct();
			record.setPayStatus(PayStatus.REFUND_SUCCESS.getCode());
			record.setStatus(OrderStatus.cancel.getCode());
			orderProductMapper.updateByExampleSelective(record,ope);
		}
		//将赠送的券修改为无效（大礼包，聚合支付，拼团盲拼）
		TicketRecord record = new TicketRecord();
		record.setStatus(-1);
		record.setOrderId(ticketOrderId);
		ticketRecordMapper.updateByOrderSelective(record);
	}

	public List<Order> getRandomList(List<Order> source, int size) {
		if (source.size() <= size) {
			Collections.shuffle(source);
			return source;
		}
		List<Order> target = new ArrayList<>(size);
		Set<Integer> set = new HashSet<>(size);
		while (set.size() < size) {
			int random = new Random().nextInt(source.size());
			if (!set.contains(random)) {
				set.add(random);
				target.add(source.get(random));
			}
		}
		return target;

	}
}
